gpt4 book ai didi

jQuery 单击事件第一次触发,但第二次则不触发

转载 作者:行者123 更新时间:2023-12-01 01:11:01 24 4
gpt4 key购买 nike

这是我正在使用的 HTML:

<ul id="categories">
<li><a href="#cargo">Cargo Trailers</a></li>
<div class="dropdown">
<ul>
<li><a href="#utility">Utility Trailers</a></li>
</ul>
</div>
</ul>

我编写了一个 jQuery 脚本来隐藏下拉 div。第一次触发单击事件时会出现下拉 div。一旦选择了下拉 div 中的 li 并与 #categories ul 中的第一个 li 交换位置,单击 li 将不会调出下拉 div。

这是 jQuery:

jQuery(document).ready(function($) {

// hide the dropdown div
$('#categories > div').hide();

/*
Click the drop down arrow function
*/
var $listHeader = $('#categories > li');

$listHeader.click(function() {

if ( $('#categories > div:hidden') ) {
//show the drop down
$('#categories > div').show();
} else {
//hide the drop down
$('#categories > div').hide();
}
});


/*
Click a list-item in the drop down function
*/
$('#categories > div a').click(function() {


/* actions to change the title to the newly selected item */
// hide the ul
$('#categories > div').hide();

// move the clicked item to the header
$(this).prependTo('#categories > li');

// move the previous title to the dropdown and sort
$('#categories > li > a:eq(1)').prependTo('#categories > div > ul > li:empty');

// Reset the listHeader variable
$listHeader = $('#categories > li');

// cancel default browser action
return false;

});
});

最佳答案

这个 $('#categories > div:hidden') 将始终返回 jQuery 对象(其计算结果为 true),即使没有与选择器匹配的元素。使用 jQuery 的 .toggle() 而不是 if...else:

$('#categories > div').toggle();

这里是 an example一起玩

<小时/>

更新以回应您的评论:更新示例 - http://jsfiddle.net/Etkjr/1/

你是对的,事件处理程序在 DOM 更改时未绑定(bind)。为了防止这种情况,您需要使用 2 个 jQuery 函数:.live().delegate。它们都监视 DOM 更改,并在 DOM 更改时将事件重新绑定(bind)到选择器。

您想要单击第一个 li 来展开下拉菜单 - 使用

$('#categories li:first').live('click', function() {})

这样,单击第一个 li 将触发您的处理程序,即使您的 li 刚刚移动到第一个位置。

$('#categories').delegate('.dropdown a', 'click', functon(evt) {})

这是 .delegate() 的示例。这意味着当有人点击 #categories 内匹配 .dropdown a 的元素时,将调用此处理程序。

这里你可以使用.live()来代替,但是.delegate更有意义。我们不是将事件处理程序分配(复制)到所有匹配元素,而是将所有点击委托(delegate)给单个事件处理程序。

我还更新了“移动”代码。这里有趣的副作用是,您不需要在第二个处理程序中使用 .hide() 下拉列表。您会看到,当您单击下拉列表中的链接时,该链接会移至第一个位置。 .live() 检测到这一点,并将 click() 处理程序分配给您刚刚单击的链接。但事件仍在传播,因此在第二个处理程序完成后,事件会冒泡到 li$('.li').live('click', ...) 执行,隐藏您的下拉 div。

希望这是有道理的。

关于jQuery 单击事件第一次触发,但第二次则不触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4763997/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com