[英]jQuery: How do I add a class to an element that has been inserted into the DOM via ajax
My page makes an ajax call and creates some markup on the page from the results. 我的页面进行ajax调用,并从结果中在页面上创建一些标记。 How do I then add a class to one of these elements.
然后,我如何将类添加到这些元素之一。 For example:
例如:
<div id="hiddenresult">
<div class="page">
<p><a id="23">Some link</a></p>
</div>
</div>
This markup has been inserted by javascript so when I do: 这个标记已经被javascript插入,所以当我这样做时:
$('#hiddenresult a#23').addClass("myClass");
It does nothing. 它什么都不做。
I want to be able to add a class to the anchor when I click a link on my page. 我希望能够在单击页面上的链接时向锚点添加类。 Something like this:
像这样的东西:
$('#button').click(function() {
$('#hiddenresult a#23').addClass("myClass");
});
The id of any dom element should always be unique and must not start with a number. 任何dom元素的id应始终是唯一的,并且不能以数字开头。 You can just try this to add the class.
你可以尝试这个来添加类。
<div id="hiddenresult">
<div class="page">
<p><a id="_23">Some link</a></p>
</div>
</div>
$('#_23').addClass("myClass");
I think you mean that you have a click handler which is not working for ajax injected elements? 我认为你的意思是你有一个点击处理程序,它不适用于ajax注入的元素? Try:
尝试:
$("#hiddenresult").delegate("a", "click", function() {
$(this).addClass("myClass");
});
Try , it will work : 试试,它会工作:
$('#button').live('click', function() {
$('#hiddenresult a#23').addClass("myClass");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.