4

私のWebページには、変数にコピーするクラス「editor」のDIVがあります。

editorTemplate = $('.editor');

DIVは次のようになります(簡略化):

<div class="editor">
  <div>
    Title: <span class="title" id="title">  the title goes here  </span><br />
    <select class="recording_list" id="recording_list">
      <option value="1">Pos 1</option>
      <option value="2">Pos 2</option>
      ...
    </select>
</div>  <!-- class=editor -->

後で、そのdivからシリーズを作成して、ページに追加します。

$(editArea).append(editorTemplate);

ここまでは順調ですね。

ただし、エディターテンプレートをページに貼り付ける前に、フィールドのID、テキスト、オプションボックスの選択された要素など、いくつかの属性を変更したいと思います。

編集テンプレートのIDは次のように変更できます

$(myEdit).attr("id", "edit" + nEditors);

しかし、テンプレートのINNER要素(IDや「タイトル」フィールドのテキストなど)にアクセスする方法がわかりません。

テンプレートがページに貼り付けられた後、私は言うことができます

$('#title').attr("id", "title" + nEditors);
$('#title').html("the new text");
...

テンプレートをページに貼り付ける前に、これらの変更を加えることはできますか?

4

4 に答える 4

4

要素を変数にコピーしていません。

editorTemplate = $('.editor');

上記は、DOM 要素を指すポインターのセットを持つ jQuery ラッパーを作成します。ラッパーを使用すると、DOM 要素を対象とする jQuery メソッドを実行できます。

それを行うと、新しいコピーではなく、DOM で現在指している要素editorTemplate.find("#title").attr("id", "newId")の属性が変更されます。id

後でこれを行うことを計画している場合:

$(editArea).append(editorTemplate);

上記はDOM要素の新しいコピーを追加するのではなく、DOM内の元の場所から参照しているDOM内の新しい場所へmovingのラッパーを介してポイントする要素になります。editorTemplateeditArea

editorTemplate後でそれらを追加するためにいくつかの要素の複製を作成することを計画している場合は、次clone()のように jQuery を使用します。

// use clone(true, true) to also clone any attached events
var editorTemplate = $('.editor').clone();

// Using .find you can change attribute in your new copy/clone
editorTemplate.find("#title").attr("id", "title" + nEditors).html("the new text");

// append your new copy/clone
$(editArea).append(editorTemplate);
于 2013-02-03T18:26:09.343 に答える
4

JQuery.children()メソッドを利用できます。

var editorTemplate = $('.editor');
editorTemplate.children('<selectors to uniquely identify the child object>').<method to update the content accordingly>

それで、私たちはこのようなことをすることができます...

count=1;
editorTemplate.children('span#title').html('<Update HTML here>').attr('id','title_'+count);

アップデート:

要素が複数のレベルにあることに気付いたので、.find()を使用すると、複数のレベルをたどって子孫要素 (孫など) も選択できるので理想的です。

于 2013-02-03T18:13:03.360 に答える
1

要素にアクセスするには、find メソッドを使用できます。

var editorTemplate = $('.editor');

$(editorTemplate).find('#title').attr('id', 'title' + nEditors).html('the new text');
于 2013-02-03T18:08:05.243 に答える
1
editorTemplate.clone()
              .attr({})
              .find("select").attr({id:"whatever"}).end()
              .find("span").....end()
              .appendTo($(editarea))

あなたがその考えを理解してくれることを願っています

于 2013-02-03T18:10:23.090 に答える