Home Web Front-end H5 Tutorial jquery 新建的元素事件绑定问题

jquery 新建的元素事件绑定问题

May 17, 2016 am 09:08 AM

       js的事件监听跟css不一样,css只要设定好了样式,不论是原来就有的还是新添加的,都有一样的表现。而事件监听不是,你必须给每一个元素单独绑定事件。


      常见的例子是处理表格的时候。每行行末有个删除按钮,点了这个能够删除这一行。

<table> 
<tbody> 
<tr> 
<td>这行原来就有</td> 
<td><buttonclass="del">删除</button></td> 
</tr> 
<tr> 
<td>这行原来就有</td> 
<td><buttonclass="del">删除</button></td> 
</tr> 
</tbody> 
</table>
Copy after login


通常,我会这么绑定

1.jQuery(function($){
2.   //已有删除按钮初始化绑定删除事件
3.    $(".del").click(function() {
4.        $(this).parents("tr").remove();
5.   });
6.});
Copy after login




对于在domready之前就存在的删除按钮,一切都很完美。但如果在domready之后用js动态添加几行,那新增的几行中的这些按钮都将失去任何作用。


如何解决这个问题?以下提供4种解决方案:



0号解决方案——onclick法
如果不顾结构与行为分离的准则的话,通常,我会这么做。
注意,此时的deltr这个function必须是全局函数,得放jQuery(function($) {})外面,放里边就成局部函数了,html里的onclick就调用不到了!

<td><buttononclick="deltr(this)">删除</button></td> 

jQuery(function($){ 
//添加行 
$("#add2").click(function(){ 
$("#table2>tbody").append(&#39;<tr><td>新增行</td><td><button nclick="deltr(this)">删除</button></td></tr>&#39;) 
}); 
}); 
//删除行的函数,必须要放domready函数外面 
function deltr(delbtn){ 
$(delbtn).parents("tr").remove(); 
};
Copy after login


1号解决方案——重复绑定法
即,在domready的时候就给已有的元素绑定事件处理函数,
而后当新增加的元素的时候再次绑定。

<td><buttonclass="del">删除</button></td> 

jQuery(function($){ 
//定义删除按钮事件绑定 
//写里边,防止污染全局命名空间 
function deltr(){ 
$(this).parents("tr").remove(); 
}; 
//已有删除按钮初始化绑定删除事件 
$("#table3 .del").click(deltr); 
//添加行 
$("#add3").click(function(){ 
$(&#39;<tr><td>新增行</td><td><button class="del">删除</button></td></tr>&#39;) 
//在这里给删除按钮再次绑定事件。 
.find(".del").click(deltr).end() 
.appendTo($("#table3>tbody")); 
}); 
});
Copy after login

2号解决方案——事件冒泡法
利用事件冒泡的原理,我们给这个按钮的祖先元素绑定事件处理函数。
然后通过event.target这个对象来判断,这个事件是不是我们要找的对象触发的。
通常可以利用一些DOM属性,比如event.target.className、event.target.tagName等之类的来判断。

<td><buttonclass="del">删除</button></td> 

jQuery(function($){ 
//第四个表格的删除按钮事件绑定 
$("#table4").click(function(e) { 
if (e.target.className=="del"){ 
$(e.target).parents("tr").remove(); 
}; 
}); 
//第四个表格的添加按钮事件绑定 
$("#add4").click(function(){ 
$("#table4>tbody").append(&#39;<tr><td>新增行</td><td><button class="del">删除</button></td></tr>&#39;) 
}); 
});
Copy after login

3号解决方案——复制事件法
上面几种方案可以说即便你没有用到jQuery库,你也能相对比较容易的实现。但这种方案相对依赖jQuery的程度更高。而且必须要求jQuery 1.2版以上。低版本jQuery需要插件。
上面两个方案都是对删除函数动了很多脑筋,换了多种触发、绑定的方式。这个方案不同,可以与平时纯静态的元素一样在domready的时候绑定。但在我们添加新行的时候我们改动一下,不再想上面那样拼接字符串来添加新行了。这回我们尝试使用复制DOM元素的方式。并且复制的时候连同绑定的事件一起复制,复制完之后再用find之类的修改内部的元素。
同时,就像这个例子,如果你会把所有元素都删除光,那template这个模板是必须的,如果不会删光,那就未必需要用template了。为了防止被误删,此处我把template设了隐藏。
我使用了jQuery中特有的clone(true)

.template{display:none;} 

<trclass="template"> 
<td>这里是模板</td> 
<td><button class="del">删除</button></td> 
</tr> 
<tr> 
<td>这行原来就有</td> 
<td><button class="del">删除</button></td> 
</tr> 
<tr> 
<td>这行原来就有</td> 
<td><button class="del">删除</button></td> 
</tr> 

jQuery(function($){ 
//第五个表格的删除按钮事件绑定 
$("#table5 .del").click(function() { 
$(this).parents("tr").remove(); 
}); 
//第五个表格的添加按钮事件绑定 
$("#add5").click(function(){ 
$("#table5>tbody>tr:eq(0)") 
//连同事件一起复制 
.clone(true) 
//去除模板标记 
.removeClass("template") 
//修改内部元素 
.find("td:eq(0)") 
.text("新增行") 
.end() 
//插入表格 
.appendTo($("#table5>tbody")) 
}); 
});
Copy after login


总评:
上面4种方案,各有优劣。
0号方案,结构与行为完全没有分离,而且污染全局命名空间。最不推荐。所以我都不把它当作一个方案来看。但对于js初学者,可以用来项目救急。
1号方案,中规中矩,没啥好也没啥不好
2号方案,这种方法充分的发挥了js事件冒泡的优势。而且效率最高。但同时由于这种方案无视了jQuery强大的选择器,所以如果涉及的元素属性要求过多就会比较麻烦了。你会徘徊在众多if的条件的是非关系之中。后来我想起来,可以用jQuery中的$(event.target).is(selector)来作为条件。这样可以极大提升开发效率,但略微降低执行效率。
3号方案,这是我认为最能体现结构与行为分离的思想的一种方案。但缺点也很明显,对于jQuery依赖性过于高了,要不就自己写一个复制连同事件一起复制的函数,但这也显然对于初学者来说异常困难。但从未来的趋势的角度来看,还是很推荐使用这种方案的。


具体选用哪一个方案,没有定数。具体看你的项目以及你js还有结构与行为分离的思想的掌握程度。最适合的才是最好的。

附加:

把3号方案改造成完美的结构行为分离的样式。
首先,带有template的是模板元素。他是一切复制的源泉,为了防止被误删,所以设为不可见。如果不会删除光,那么这个模板元素也是可选的。因为你可以复制任何一个已经存在的用于循环元素。
其次,给每个重复的元素加上一个repeat,方便用于删除按钮找到这一级元素。这个是可选的,有时候并不需要。
最后是给每一个要修改的元素加上一个类,便于用find找到。比如我这里就家了content类,新增加的可以修改里边的值。
这样一个完美的结构与行为分离的案例就完成了。

<tableid="table6"> 
<tbody id="tbody6"> 
<tr class="template repeat"> 
<td class="content">这里是模板</td> 
<td><button class="del">删除</button></td> 
</tr> 
<tr class="repeat"> 
<td class="content">这行原来就有</td> 
<td><button class="del">删除</button></td> 
</tr> 
<tr class="repeat"> 
<td class="content">这行原来就有</td> 
<td><button class="del">删除</button></td> 
</tr> 
</tbody> 
<tfoot> 
<tr> 
<td> </td> 
<td><button id="add6">添加</button></td> 
</tr> 
</tfoot> 
</table> 

jQuery(function($){ 
//第六个表格的删除按钮事件绑定 
$("#tbody6 .del").click(function() { 
$(this).parents(".repeat").remove(); 
}); 
//第六个表格的添加按钮事件绑定 
$("#add6").click(function(){ 
$("#tbody6>.template") 
//连同事件一起复制 
.clone(true) 
//去除模板标记 
.removeClass("template") 
//修改内部元素 
.find(".content") 
.text("新增行") 
.end() 
//插入表格 
.appendTo($("#tbody6")) 
}); 
});
Copy after login

同样,这段js也适用于如下的html结构

<ulid="tbody6"> 
<li class="template repeat"> 
<span class="content">这里是模板</span> 
<span><button class="del">删除</button></span> 
</li> 
<li class="repeat"> 
<span class="content">这行原来就有</span> 
<span><button class="del">删除</button></span> 
</li> 
<li class="repeat"> 
<span class="content">这行原来就有</span> 
<span><button class="del">删除</button></span> 
</li> 
</ul> 

<script type="text/javascript"></script>
Copy after login

以上就是jquery 新建的元素事件绑定问题的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

In-depth analysis: jQuery's advantages and disadvantages In-depth analysis: jQuery's advantages and disadvantages Feb 27, 2024 pm 05:18 PM

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

See all articles