Home > Web Front-end > JS Tutorial > How to solve the problem that jquery on does not take effect

How to solve the problem that jquery on does not take effect

藏色散人
Release: 2020-11-30 10:58:28
Original
3797 people have browsed it

The solution to jquery on not taking effect: first open the corresponding code file; then use the correct method "$('body').on('click', '#test .evt', function() {alert($(this).text())});” Just use on.

How to solve the problem that jquery on does not take effect

The operating environment of this tutorial: Windows 7 system, jquery version 1.10.0. This method is suitable for all brands of computers.

Recommendation: "jquery tutorial"

jquery's on() binding method is invalid

The element in front of on It must also exist in the dom when the page is loaded. Dynamic elements or styles can be placed in the second parameter of on

The jQuery on() method is an officially recommended method for binding events. Use the on() method to bind specified events to dynamic elements created dynamically in the future, such as append, etc.

<div id="test">
<div class="evt">evt1</div>
</div>
Copy after login

Wrong usage, the following method only binds the click event for the first class div of evt, while the div dynamically created using append is not bound.

<script>
// 先绑定事件再添加div
$(&#39;#test .evt&#39;).on(&#39;click&#39;, function() {alert($(this).text())});
$(&#39;#test&#39;).append(&#39;<div class="evt">evt2</div>&#39;);
</script>
Copy after login

The correct usage is as follows :

<script>
$(&#39;body&#39;).on(&#39;click&#39;, &#39;#test .evt&#39;, function() {alert($(this).text())});
$(&#39;#test&#39;).append(&#39;<div class="evt">evt2</div>&#39;);
</script>
Copy after login

checkbox radio selection setting If is added dynamically, you can do this

$("#grid").on("click","input[name=ck]",function(){
$("input[name=ck]").not(this).prop("checked",false);
});
Copy after login

Note: $(selector).on (event,childSelector,data,function,map)

The above is the detailed content of How to solve the problem that jquery on does not take effect. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source: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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template