0

に割り当てることは可能select()ですreplaceWith()か?

$('#foo').one('click', function() {
 $(this).replaceWith('<textarea id="copy">'+$(this).text()+'</textarea>');
});

$('#copy').click(function() {
 $(this).select();
});

私は上記のコードを試しましたが、うまくいきません(これはreplaceWith()架空の要素であるためだと思います(私が言っていることを理解した場合))。

しかし、私はそれを中に置くことによってそれを機能させonclick="this.focus();this.select()"ましたreplaceWith()

$('#foo').one('click', function() {
 $(this).replaceWith('<textarea id="copy" onclick="this.focus();this.select()">'+$(this).text()+'</textarea>');
});

replaceWith()しかし、最初のコードがやろうとしているように、コードの外でそれを好むでしょう。

4

1 に答える 1

1

元のコードでは、クリックイベントを存在しないオブジェクト(バインド時に存在しない)にバインドしています。

以下は、textareaをDOMに挿入した、クリックイベントをバインドし、機能するはずです。

$('#foo').one('click', function() {
  $(this).replaceWith('<textarea id="copy">'+$(this).text()+'</textarea>');

  // at this point, the textarea exists and the binding will work.
  $('#copy').click(function() {
    $(this).select();
  });
});

もう1つの方法は、ドキュメントオブジェクトの#copyをクリックするためにon()を使用してバインドすることです。

$('#foo').one('click', function() {
  $(this).replaceWith('<textarea id="copy">'+$(this).text()+'</textarea>');
});

// in this case, it will work even if #copy is non-existant at the time of binding
$(document).on('click', '#copy', function() {
  $(this).select();
});
于 2012-11-04T15:33:56.300 に答える