由replace()添加的元素不可点击,即使使用.on()也是如此

时间:2014-10-28 21:11:12

标签: javascript jquery events jquery-events

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

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

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

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

但这也行不通,感觉我错过了什么。

2 个答案:

答案 0 :(得分:1)

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

所发生的情况是,您不会将替换的文本作为html添加到页面中。

当你使用&#34;替换&#34;函数的字符串对象,你操纵文本,只是文本,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.

答案 1 :(得分:0)

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

&#13;
&#13;
var mytext = $('p').text(),
    changes = mytext.replace("someword","<span class='clickme'>someword</span>");

$('p').html(changes);

$(document).on("click",".clickme",function(){
    alert("meow");
})
&#13;
.clickme{
  background: #f00;
  color: #fff;
  cursor: pointer;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>


<p>Lorem ipsum dolor someword sit amet</p>
&#13;
&#13;
&#13;