replaceWith和textarea选择 [英] replaceWith and textarea select

查看:83
本文介绍了replaceWith和textarea选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将select()分配给replaceWith()?

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

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

我已经尝试了上面的代码,但是没有用(我认为这是因为replaceWith()是一个虚构的元素(如果您明白我的意思)).

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)).

但是我通过将onclick="this.focus();this.select()"放在replaceWith()

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

,但更喜欢replaceWith()代码之外的代码,就像第一个代码正在尝试做的那样.

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

推荐答案

在您的原始代码中,您将click事件绑定到了一个不存在的对象(绑定时不存在).

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

下面的示例将将文本区域插入DOM后绑定单击事件 ,并且应该可以正常工作.

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

另一种方法是使用on()绑定任何在文档对象上#copy的单击.

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

这篇关于replaceWith和textarea选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆