このように書くだけです:
var method = "wrap";
jQuery('.container')[method]("<div>Hello World</div>");
オブジェクトのプロパティにアクセスするには、2 つの方法があります。ドット表記または角括弧表記のいずれか
obj.property
obj['property']
var propName = "property"
obj[propName]
編集
ここに MDNメンバーオペレーターへのリンクがあります
あなたのコードが何をするかについての簡単な説明:
jQuery('.container')+[method]+("<div>Hello World</div>");
それは3つの要素の追加です:
- の結果セット
jQuery('.container')
- 1
Array
つの要素を含む[method]
- の
String
"<div>Hello World</div>"
この結果は実装によって異なりますが、おそらく次のようになります。
"[object Object].wrap<div>Hello World</div>"
+-------------+
+---+
+--------------------+
toString
JavaScript エンジンは通常、別の方法で要素を追加できない場合に要素を呼び出すため、結果はこのようになります。
編集
編集された質問への更新:
element.parent().parent().wrap()
たとえば、次のようになります。
element['parent']()['parent']().wrap()
また
element['parent']().parent()['wrap']()
またはその他の任意の組み合わせ obドットまたはブレース表記
1 つの文字列として表し.parent().parent().wrap()
、これをアクセスとして使用します。しかし、これはそのようには機能しません。ドット表記またはブレース表記は、指定された要素のプロパティのみを返します。したがって、呼び出したこの返されたオブジェクトと、呼び出しparent()
たその返されたオブジェクトの を返します。parent
jQuery('.container')
parant()
wrap()
したがって(最後の関数呼び出しだけが引数を持つと仮定すると)、次のようなものが必要になります。
function chainedFunctionCall( obj, chain, arguments) {
var curr = obj;
var splitChain = chain.split("."); //split the 'call chain' passed a strings by '.' (the dot in the string has nothing to do with the dot notation)
//iterate over the resulting array (except the last one where we need to pass the arguments to
for( var i=0 ; i<splitChain.length-1 ; i++ ) {
//call the function by the given name in the chain and store the result as current object
curr = curr[splitChain[i]]();
}
//when we reached the last name in the chain call that function using `apply` so that we can pass the arguments we got as array to the function call, and call it in the context of the current object.
return curr[splitChain[i]].apply(curr,arguments);
}
var obj = $(".container");
var callChain = "parent.parent.wrap";
chainedFunctionCall( obj, callChain, ["<div>your argument you pass there</div>"]);