【问题标题】:replaceWith and textarea selectreplaceWith 和 textarea 选择
【发布时间】:2012-11-04 23:33:56
【问题描述】:

是否可以将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() 代码之外,就像第一个代码试图做的那样。

【问题讨论】:

    标签: jquery replacewith


    【解决方案1】:

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

    以下绑定点击事件将文本区域插入 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();
      });
    });
    

    另一种方法是使用 on() 对文档对象上的 #copy 进行任何点击进行绑定。

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

    【讨论】:

    • 我意识到该对象不存在,因为这就是我所说的“虚构元素”的意思,只是不知道正确的术语,所以只需将选择代码移动到 #foo 单击即可,谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2017-04-13
    • 2016-06-12
    • 2018-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-07
    • 1970-01-01
    相关资源
    最近更新 更多