如何访问jquery动态生成的元素 [英] How to access jquery dynamically generted elements

查看:74
本文介绍了如何访问jquery动态生成的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码。

 < 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆