[英]jQuery toggle dynamically created elements
我有这样的东西,但是不起作用:
<!-- ... code .. -->
var id = 0;
data.forEach(function(item, i) {
id = id+1;
$( ".button-" + id ).click(function() {
$( ".button-" + id ).toggle();
});
<!-- ... code .. -->
我想要的是:有一些DIV,例如button-1,button-2 ...等。 我进行了切换,并希望通过此循环使其自动化,因为内容是动态生成的。 但这似乎是错误的方法...在此循环中,它不起作用。
那么如何动态地为button-1,button-2,...切换?
就是这样,这似乎是错误的:
$( ".button-" + id ).click(function() {
$( ".button-" + id ).toggle();
编辑
好吧,也许我的问题有点混乱😉谢谢您到目前为止的回答,我非常感谢! 但是对于我来说,没有正确的答案……所以现在又一再具体了:
我有一些带有实物图标的按钮,应该可以在单击时更改其状态。
<a href="" class="likebutton-1"><i class="material-icons">favorite</i></a>
<a href="" class="likebutton-1" style="display:none;"><i class="material-icons">favorite_border</i></a>
HTML内容是动态生成的,因此有一个likebutton-1,likebutton-2 ...
然后是另一个DIV,显示了很多赞:
<div class="likes-1">99 likes</div>
<div class="likes-1" style="display:none;">100 likes</div>
DIV都在外部容器中。
这是我的jQuery代码:
$( ".likebutton-1" ).click(function() {
$( ".likebutton-1" ).toggle();
$( ".likes-1" ).toggle();
});
好的,该代码对我有用。 图标从“收藏夹”切换为“ favourite_border”,“赞”从99切换为“ 100 ...”(这只是一个演示应用程序,因此不必真正计算“赞”数)
但是我也想动态生成该jQuery代码,这是行不通的...现在,我必须手动为likebutton-1,likebutton-2设置切换开关...
我想这就是你的意思:D
https://jsfiddle.net/1eo4b33m/1/
$("[class*=button-]").click(function(){
$(this).toggle()
})
根据您的最新更新,我建议您对HTML标记进行一些结构性更改。
而不是使用:
<a href="" class="likebutton-1"><i class="material-icons">favorite</i></a>
<a href="" class="likebutton-1" style="display:none;"><i class="material-icons">favorite_border</i></a>
我建议仅使用一个元素-可以防止样式问题。 此外,如果动态生成这些段,则删除-1
或-X
后缀,否则需要大量(动态创建)事件侦听器。
像这样做:
<a href="#" class="likebutton"><i class="material-icons icon-fav">favorite</i></a>
我将class icon-fav
添加到您的元素中,以便更轻松地进行访问。
现在,我们对您喜欢的部分进行相同的操作,并改善代码结构。 从文本中分开喜欢计数(即数字)。 因此,我们可以轻松地增加或减少此数字。
<div class="likes"><span class="likes-count">99</span> likes</div>
因为您提到您是自动生成此细分的,所以我假设您在这些元素周围有一个或类似的符号,例如:
<div class="parent-container">
<a href="#" class="likebutton"><i class="material-icons icon-fav">favorite</i></a>
<div class="likes"><span class="likes-count">99</span> likes</div>
</div>
现在,我们关心剩下的部分-JavaScript。
由于您的类的-x
后缀已删除,因此我们需要进行树遍历-否则,当单击其中的一个元素时,我们将立即更改所有元素。 您可以在此处找到有关jQuery Tree Traversal的更多信息。
$(".likebutton").click(function() {
var $parent = $(this).closest(".parent-container");
var likes = parseInt($parent.find(".likes-count").text());
if($parent.find(".icon-fav").text() == "favorite") {
$parent.find(".icon-fav").text("favorite_border");
$parent.find(".likes-count").text(++likes);
}
else {
$parent.find(".icon-fav").text("favorite");
$parent.find(".likes-count").text(--likes);
}
});
此事件侦听器使用.closest()
方法找到其父容器,即使您的代码嵌套得更多,它也可以使此代码正常工作。 $parent
变量是所有后续查询的搜索基础。 我使用.find()
一路向上遍历-如果有必要的话-因为您可能具有更多的嵌套结构。
这是一个工作的jsfiddle ! 试试看。
试一试吧! :)
$("[class*='button-']").click(function(){
$(this).toggle();
});
您必须在这里使用闭包,
var id = 0;
data.forEach(function(item, i) {
id = id+1;
var bindEvents = function theOutterFunction() {
return function() {
$( ".button-" + id ).click(function() {
$( ".button-" + id ).toggle();
}
}();
bindEvents();
});
你有一些好的答案。 但看起来您好像错过了这么简单。 您需要使用的是jQuery的.on
方法。 您可以查看此SO问答,以获取有关设置动态事件的更多信息。
但是,总而言之,这意味着:“将动态元素的事件分配给静态父对象。” 在此处阅读有关“什么是动态和静态”的更多信息。 简而言之,动态方式是在页面加载后创建的。
因此,从本质上讲,您可以使用Jamie Phan
给出的答案 ,您只需要了解如何实现它即可。
您真正需要的只是一个“ 静态父母 ”。 这是加载页面时HTML中已经存在的元素。 我个人经常使用DOM对象,但是,最佳实践是使用ID作为其近亲。 例如,如果您的HTML看起来像:
<div>
<h1>Dynamic buttons added below</h1>
<ul id="divDyno"><!-- Buttons will be added here --></ul>
</div>
然后,您的静态父对象将是<div id="divDyno"...
,可以使用字符串'#divDyno'
进行选择。 因此,您的代码如下所示:
$('#ulDyno').on('click', '[class*=button-]', function(e) {
$(this).toggle();
})
以下是如何轻松实现这些技术的快速示例。 我添加了一些内容,以便您可以看到它的全部功能,但是我将尝试深入解释所有内容。
修改为仅切换按钮的类(也称为更改状态)
/** This will be the event fired when clicking on a "dynamically" created button **/ function button_click_event() { // only need use "this", no need for ID. // 'this' is the button html element itself $(this).toggleClass('black white'); } /** This event will dynamically create buttons **/ function create_button() { // first I get the length of how many buttons exist, // simply to add to the button text var len = $('ul li').length, // then I create a <li> to append to the <ul> li = $('<li />').appendTo('ul'), // then, of course, I create the <button> and add it to the <li> btn = $('<button />').text('Button '+len).addClass('button-'+len).appendTo(li); // now we'll give the button a class for color btn.addClass(len%2 ? 'black': 'white') } /** This will simply show all "toggled" buttons **/ function show_buttons() { $('ul button').show(); } $(function() { // As per the previously mentioned example // In jQuery, you can set events for a dynamic element by using a static parent. $('#ulDyno').on('click', '[class*=button-]', button_click_event) // In the following case, I'll simply use the DOM for brevity, // but it's still best to use a "static" element with an ID // This event is simply for the "Add" button. To "dynamically" create buttons. $(document).on('click', '#btnAdd', create_button)// notice i didn't close with a ";" // With no close, the return is "$(document)", So I can write more code attached to it. // This event will show any "toggled" buttons .on('click', '#btnShow', show_buttons); });
html, body { font-size: 20px; width: 100%; } html, body, table { height: 100%; margin: 0 auto; padding: 0; text-align: center; } div { left: 1em; position: fixed; top: 1em; } ul { margin: 0 auto; padding: 0; } li { list-style: none; margin: .5em auto; padding: 0; } button { padding: .5em .8em; } .black { background-color: #000; color: #fff } .white { background-color: #fff; color: #000 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div><button id="btnAdd">Add Buttons</button><button id="btnShow">Show All Buttons</button></div> <table> <tr> <td> <br /> <ul id="ulDyno"></ul> </td> </tr> </table>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.