<div id="tours">
<h1>Guided Tours</h1>
<ul>
<li class="usa tour" data-discount="299">
<h2>New York, New York</h2>
<span class="details">$1,899 for 7 nights</span>
<button class="book">Book Now</button>
</li>
<li class="europe tour" data-discount="176">
<h2>Paris, France</h2>
<span class="details">$2,299 for 7 nights</span>
<button class="book">Book Now</button>
</li>
<li class="asia tour" data-discount="349">
<h2>Tokyo, Japan</h2>
<span class="details">$3,799 for 7 nights</span>
<button class="book">Book Now</button>
</li>
</ul>
</div>
上面是 HTML 代码,下面是 DOM 操作部分。
$(document).ready(function(){
$("li.tour button.book").on("click", function(){
var tour = $(this).closest(".tour");
var discount = tour.data("discount");
var message = $("<span>Call 1-555-jquery-air for a $" + discount + "</span>");
tour.append(message);
$(this).remove();
});
});
上面的代码工作正常。但似乎正确的方法如下,他们称之为事件委托
$(document).ready(function(){
$("li.tour").on("click", "button", function(){
var tour = $(this).closest(".tour");
var discount = tour.data("discount");
var message = $("<span>Call 1-555-jquery-air for a $" + discount + "</span>");
tour.append(message);
$(this).remove();
});
});