2

次のように使用する変数にメソッドを追加しようとしています。

var method = ".wrap";   
jQuery('.container')+[method]+("<div>Hello World</div>");

基本的にそれがすべきことは次のとおりです。

jQuery('.container').wrap("<div>Hello World</div>");

しかし、それは機能しません。エラーはありません。Hello World div がページに追加されていません。これが元の質問http://goo.gl/MQ2trです。もっと簡単な言葉でもう一度質問すると思いました。

更新 変数内に単一のメソッドがある限り、ブラケット表記でうまく機能しますが、.parent().parent().wrap()どのように機能させることができますか? すべてのドットを削除しようとしましたが、エラーが発生しましたUncaught TypeError: Object [object Object] has no method 'parent()parent()wrap'

これが私のリストフォームが今どのように見えるかです

 <select name="lu_ban_data[method]" id="lu_ban_data" />
        <option value="append">Append</option>
        <option value="prepend">Prepend</option>
        <option value="wrap">Wrap</option>
        <option value="parent()parent()wrap">Parent</option>
</select>
4

1 に答える 1

5

このように書くだけです:

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つの要素の追加です:

  1. の結果セットjQuery('.container')
  2. 1Arrayつの要素を含む[method]
  3. String "<div>Hello World</div>"

この結果は実装によって異なりますが、おそらく次のようになります。

"[object Object].wrap<div>Hello World</div>"
 +-------------+
                +---+
                     +--------------------+

toStringJavaScript エンジンは通常、別の方法で要素を追加できない場合に要素を呼び出すため、結果はこのようになります。

編集

編集された質問への更新:

 element.parent().parent().wrap()

たとえば、次のようになります。

 element['parent']()['parent']().wrap()

また

 element['parent']().parent()['wrap']()

またはその他の任意の組み合わせ obドットまたはブレース表記

1 つの文字列として表し.parent().parent().wrap()、これをアクセスとして使用します。しかし、これはそのようには機能しません。ドット表記またはブレース表記は、指定された要素のプロパティのみを返します。したがって、呼び出したこの返されたオブジェクトと、呼び出しparent()たその返されたオブジェクトの を返します。parentjQuery('.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>"]);
于 2013-07-15T15:28:49.530 に答える