replaceWith and textarea select

我们两清 提交于 2019-12-13 08:17:21

问题


Is it possible to assign select() to a replaceWith()?

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

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

I've tried the above code but it dosen't work (I assume this is because the replaceWith() is a fictional element (if you get what I mean)).

I have however got it working by placing onclick="this.focus();this.select()" inside the replaceWith()

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

but would prefer it outside of the replaceWith() code like the first code is trying to do.


回答1:


In your original code, you are binding the click event to a non-existant object (non-existant at the time of binding).

The following binds the click event after inserting the textarea into the DOM and should work.

$('#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();
  });
});

Another way is bind using on() for any click on #copy on the document object.

$('#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();
});


来源:https://stackoverflow.com/questions/13219593/replacewith-and-textarea-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!