宝哥软件园

jQuery实现获取一个动态添加标签对象的例子

编辑:宝哥软件园 来源:互联网 时间:2021-08-31

本文阐述了jQuery获取动态添加标签对象的实现。分享给大家参考,如下:

Jquery不能直接向网页动态添加点击事件并获取对象

一般来说,js通过向标签添加onclick属性来调用动态添加的组件,这是一种常见的方法,如下所示:

进入点击模式

!doctype html lang=' en ' head meta charset=' utf-8 ' titlewww.jb51.net jquery动态获取事件/title/headloddivid=' test '/div/body script type=' text/JavaScript ' src=' http :https://cdnjs . cloudflare.com/Ajax/libs/jquery/3 . 3 . 1/jquery . min . js '/script script var html=' ';//声明要存储html的变量(I=0;i=10I){ html=html ' button onclick=' BTN点击(此)' button ' I '/button/br ';} $('#test ')。html(html);函数BTN click(e){ console . log(e . TextContent);//get button text }/script/html现在jquery已经到了3版,官方已经放弃了live方法,建议使用on方法。语法是

$(“选择器”)。on('click ',' select type ',function (e){代码片段}

Jquery无法动态获取网页中的标签,但需要先获取网页的固定标签,然后再获取里面的其他标签。因此,上面代码中带有id测试的div是固定的。

!doctype html lang=' en ' head meta charset=' utf-8 ' titlewww.jb51.net jquery动态获取事件/title/headloddivid=' test '/div/body script type=' text/JavaScript ' src=' http :https://cdnjs . cloudflare.com/Ajax/libs/jquery/3 . 3 . 1/jquery . min . js '/script script var html=' ';//声明要存储html的变量(I=0;i=10I){ html=html ' button button ' I '/button/br ';} $('#test ')。html(html);$('#test ')。on('click ',' button ',function(e){ console . log($(this));});/script/html使用http://tools.jb51.net/code/HtmlJsRun测试运行效果:

这样写很简单,选择类型中的按钮可以进一步限制,例如button[class=test],也就是动态创建的按钮,其类为text。

要实现单双号,只需要加上“:偶数”,按钮[class=test] :偶数,或者测试后的奇数偶数

修改后的示例代码如下:

!doctype html lang=' en ' head meta charset=' utf-8 ' titlewww.jb51.net jquery动态获取事件/title/headloddivid=' test '/div/body script type=' text/JavaScript ' src=' http :https://cdnjs . cloudflare.com/Ajax/libs/jquery/3 . 3 . 1/jquery . min . js '/script script var html=' ';//声明要存储html的变量(I=0;i=10I){ html=html ' button class=test button ' I '/button/br ';} $('#test ')。html(html);$('#test ')。on('click ',' button[class=test]:even ',function(e){ console . log($(this));});/script/html继续使用http://tools.jb51.net/code/HtmlJsRun测试jquery动态获取odd对象的运行效果:

更多对jQuery感兴趣的读者,请查看本站话题:《jQuery常见事件用法与技巧总结》、《jQuery常用插件及用法总结》、《jQuery操作json数据技巧汇总》、《jQuery扩展技巧总结》、《jQuery常见经典特效汇总》、《jquery选择器用法总结》、0103010。

希望本文对大家的jQuery程序设计有所帮助。

更多资讯
游戏推荐
更多+