【问题标题】:Elements added by replace() aren't clickable, even with .on()replace() 添加的元素不可点击,即使使用 .on()
【发布时间】:2014-10-28 21:11:11
【问题描述】:

我正在尝试使用.replace 创建一些我可以稍后单击的跨度:

mytext.replace("someword","<span class='clickme'>someword</span>")

它确实正确地创建了跨度,但我无法让它们触发 jQ 事件。我试过了:

$(document).on("click",".clickme",function(){
    alert("meow")
})

但这也不起作用,感觉就像我错过了一些东西。

【问题讨论】:

  • 什么是mytext? - 你有没有重新附加到 DOM?您是否检查过这些跨度是否确实存在?
  • 你能用 jsFiddle.net 示例或堆栈 sn-p 重新创建问题吗?
  • 在你使用replace()之后你真的插入了html吗?显示更多代码
  • 您的问题的借口有问题,因为您显示的.on() 的委托形式适用于动态创建的内容。我的猜测是你实际上并没有像你想象的那样修改 DOM。如果您需要进一步的帮助,请显示该代码的其余部分。更好的是,在 jsFiddle 中重现您的简单问题。
  • JSFiddle 上的工作示例...jsfiddle.net/dowa8nhr

标签: javascript jquery events jquery-events


【解决方案1】:

JSBIN http://jsbin.com/hejefayebi/1/edit?html,js,output

发生的情况是您没有将替换的文本作为 html 添加到页面中。

看,当您使用字符串对象的“替换”功能时,您正在操作文本,只是,文本,replace function 返回一个带有操作文本的新字符串,您需要将该文本插入到html 以某种方式。

即如果您在以下文本中替换 foo:

var justText = "Hi I'm foo"; // Just some text
// First the replace function returns a new string, it does not modify the original string, so you have to reassign the value
justText = justText.replace("foo", "<span>foo</span>"); // replace will return "Hi I'm <span>foo</span>", but you need to assign it.
// Assign the text to a paragraph
var p = document.getElementById("paragraph");
// Then because you want to insert new HTML DOM elements into an existing element
// you have to use either the "innerHTML" property of HTML elements, or the "html" jQuery function (which use innerHTML internaly);
p.innerHTML = justText; // Once you have inserted the DOM elements, the click bindings will be attached.

【讨论】:

    【解决方案2】:

    如果您将替换的文本重新应用于您对文本进行采样的元素,它应该可以工作:)

    var mytext = $('p').text(),
        changes = mytext.replace("someword","<span class='clickme'>someword</span>");
    
    $('p').html(changes);
    
    $(document).on("click",".clickme",function(){
        alert("meow");
    })
    .clickme{
      background: #f00;
      color: #fff;
      cursor: pointer;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    
    
    <p>Lorem ipsum dolor someword sit amet</p>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-16
      • 1970-01-01
      • 2013-04-05
      • 1970-01-01
      • 2013-08-07
      • 1970-01-01
      • 1970-01-01
      • 2021-07-08
      相关资源
      最近更新 更多