如何访问jquery动态生成的元素 [英] How to access jquery dynamically generted elements
问题描述
< div id =static_element>< / div>
< script>
$(document).ready(function()
{
$(#static_element)。html(< b class =dynamic_element>测试< / b> );
//这行不会工作
$(。dynamic_element)。css({color:red});
})
< / script>
我想使用类dynamic_element访问标签b,但我不能因为它是动态生成。
任何想法?
Thanks $ / $>
$(#static_element)。html(< b class ='dynamic_element'>测试< / b>);
可以使用。元素由脚本生成并不重要,jQuery选择器将匹配在调用DOM时存在于DOM中的所有元素。唯一的罪魁祸首是使用Ajax函数,如加载。使用这些方法添加到DOM的元素不会显示方法调用的时间,但会在请求完成时异步执行。幸运的是,有些回调可以用于这种情况。
I have this code.
<div id="static_element"></div>
<script>
$(document).ready(function()
{
$("#static_element").html("<b class="dynamic_element">Test</b>");
//this row wont work
$(".dynamic_element").css({"color":"red"});
})
</script>
i want to access the tag "b" with the class "dynamic_element" but i cant because it was dynamically generated.
Any ideas? Thanks
This:
$("#static_element").html("<b class='dynamic_element'>Test</b>");
will work. It doesn't matter that the element is generated by script, jQuery selectors will match all elements that are present in the DOM at the time they are called. The only culprit is with Ajax functions, like load. Elements added to the DOM with these methods do not appear the time the methods are called, but asynchronously, when the request is completed. Luckily, there are callbacks that you can use for such cases.
这篇关于如何访问jquery动态生成的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!