简体   繁体   English

jQuery:如何通过ajax将一个类添加到已插入DOM的元素中

[英]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.

相关问题 将元素插入DOM后,如何对元素执行jQuery函数? - How do I perform a jQuery function on an element after it has been inserted into the DOM? jQuery调用已由ajax加载或通过html()方法插入的div元素 - jQuery calling div element that has been loaded by ajax, or inserted via html() method jQuery:是否已通过.wrap()添加到DOM上的jQuery元素上的类? - jQuery: Toggle class on jQuery element that has been added to the DOM via .wrap()? 通过动态插入的DOM元素进行AJAX调用,是否需要使用Mutation Observer? - Make AJAX call via dynamically inserted DOM element, do I have to use a Mutation Observer? 如何使用jQuery添加DOM元素? - How do I add a DOM element with jQuery? 保存已插入DOM的jquery对象 - Save jquery object that has been inserted into DOM 如何在将通过AJAX加载的DOM元素上启动jQuery插件(sequence.js)? - How do I initiate a jQuery plugin (sequence.js) on a DOM element that will be loaded via AJAX? 将jquery-ui自动完成功能所属的对象/ dom元素应用于所有输入后,如何引用它 - How do I reference the sepcific object/dom element that an jquery-ui autocomplete function belongs to, when it has been applied to all inputs jQuery在AJAX插入的DOM元素上失败 - jQuery fails on DOM element inserted by AJAX 在将jQuery创建的元素插入DOM树之前,是否可以获取它的HTML? - Is it possible to get the HTML of a jQuery created element before it has been inserted into the DOM Tree?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM