1

#content と #contentSwap の 2 つの div があります。一部のデータを #contentSwap にロードし、いくつかの操作を実行してから、#content と交換しています。html() 関数を使用して 2 つを交換していましたが、これが問題を引き起こしていることに気付きました: click() を使用して #contentSwap でアンカーに割り当てていた関数が失われていました。コードの例を次に示します。

$('#contentSwap').html(data);

$('#contentSwap a').each(function(){
 $(this).click(function(){
  // Do whatever
 });
});

$('#content').html($('#contentSwap').html());
$('#contentSwap').html("");

これ以降、#content では click() で割り当てた関数が動作しません。

ただし、attr() 関数を使用して各 div の id を変更すると、click() 関数が固執します。しかし、これは毎回うまくいくわけではなく、#content や #contentSwap などの複数のコピーを含むあらゆる種類のバグを引き起こします。そのためのコードは次のとおりです。

$('#content').attr("id", "contentSwap1");
$('#contentSwap').attr("id", "content");
$('#contentSwap1').attr("id", "contentSwap");
$('#contentSwap').html("");

割り当てた click() 関数を失わずに #content と #contentSwap を効果的に交換するにはどうすればよいですか?

4

4 に答える 4

1

I think what you need is:

$('#contentSwap').contents().appendTo('#content');

See: http://jsfiddle.net/thirtydot/jHSwY/

.contents() is used to get every child (including text nodes) of #contentSwap. The children are then moved inside #content, using .appendTo() (see the sentence containing "it will be moved into the target").

于 2012-05-11T00:34:48.387 に答える
1

何をしようとしているのかはわかりませんが、 に割り当てられたクリック ハンドラーが#contentSwap突然 で機能し始めることはありません#content

後で他の目的で要素を使用しない場合は、#contentSwap要素全体を 内#contentに移動し、委任されたイベント ハンドラーを使用して、次のように機能することを確認できます。

$('#contentSwap').html(data);

$('#contentSwap a').each(function(){
   $(document).on('click', this, function(){
       //document should be replace with nearest non dynamic parent
       //do your thing
   });
});

$('#content').empty().append($('#contentSwap'));
于 2012-05-11T00:13:53.713 に答える
0

これを考え出した!私が提供したコードの 2 番目のブロックは機能していましたが、#contentSwap div は #content div と同じ場所にありませんでした。私はそれを適切なスペースに移動し、すべてが素晴らしいものになりました.

http://www.tylergerard.com

于 2012-05-11T14:05:38.163 に答える
0

これは、イベント委任と呼ばれます。基本的に、そのコンテンツをプログラム的/動的に生成しているため、デフォルトのイベント バインディングは機能しなくなります。 .liveは非推奨ですが、次のものを使用できます。

 $(#contentSwap a).on("click", function(){
  // Do whatever
 });

また、そのeach関数は何もしていないようで、スキップできると確信しています。

于 2012-05-11T00:23:40.337 に答える