gpt4 book ai didi

jQuery 仅在第一次单击时防止默认

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

我一直在研究一些 jQuery,以便为我的客户购物网站提供附加功能。我被要求创建一个“快速购买”按钮,该按钮位于从 Locatya 拉入的类别页面上的产品顶部 - 到目前为止非常简单。

对于桌面站点,以下代码可以完美运行:

jQuery('#main_cat_prods').delegate('img', 'mouseenter', function(){
var $skuID = this.src.match(/[a-z][a-z][a-z]\d\d\d\d\d/)[0];

if ( !jQuery('#QuickBuyProdBox').length ) {
jQuery(this).closest('.image').prepend('<div id="QuickBuyProdBox">');
};
jQuery("#QuickBuyProdBox").click(function(){
jQuery.event.trigger('lightbox', $skuID);
});
jQuery('.image, #QuickBuyProdBox').mouseleave(function(){
jQuery('#QuickBuyProdBox').remove();
});
});

现在,当尝试在平板电脑上开发略有不同的功能时,困难就来了;我的客户希望单击一下即可将 QuickBuyProdBox 添加到前面,然后再单击一下即可:

如果在 QuickBuyProdBox 外部单击,则继续正常访问产品页面如果单击 QuickBuyProdBox,则启动灯箱。

我首先遇到的困难是:

为了防止类别页面上img的默认行为,我尝试过preventDefault,但这会停止main_cat_prods div上的所有点击事件。我还尝试了第一个实例的绑定(bind)点击,然后取消绑定(bind)它,这似乎也不起作用:

jQuery("#main_cat_prods").bind('img', 'click', function( event) {
if ( !jQuery('#QuickBuyProdBox').length ) {
jQuery(this).closest('.image').prepend('<div id="QuickBuyProdBox">');
};
console.log("this works");
event.preventDefault();
jQuery(this).unbind( event );
});

总而言之,上面的代码不起作用。我需要能够:

单击 main_cat_prods div 并在前面添加 QuickBuyProdBox 时阻止默认功能。能够单击 main_cat_prods 或 QuickBuyProdBox通过单击(此)img 外部或单击其他产品来删除 QuickBuyProdBox。

有什么建议吗?

如果这没有意义,请告诉我,我可以尝试重新措辞!

干杯,迈尔斯

最佳答案

使用 $.data 存储计数器,然后在第一次点击时递增计数器。
在事件处理程序内,将防止默认逻辑包装在 if 内,该逻辑在继续之前检查计数器值。

jQuery("#main_cat_prods img").data('clicked', 0);
jQuery("#main_cat_prods").bind('img', 'click', function( event) {
var state = $(this).data('clicked') || 0;
if(state === 0){
// this will only happen the first time
event.preventDefault();
state++; // <-- we increment the state
$(this).data('clicked', state);// <-- and store it back in data
}
// other code
});

这还有一个额外的好处,即不需要您声明全局变量。

<小时/>

编辑

这可能效果更好:

jQuery("#main_cat_prods img").data('clicked', 0);
jQuery("#main_cat_prods").bind('img', 'click', function( event) {
var state = $(this).data('clicked') || 0;
if(state === 0){
// this will only happen the first time
event.preventDefault();
event.stopPropagation();
state++; // <-- we increment the state
$(this).data('clicked', state);// <-- and store it back in data
return; // <-- we stop the rest of the handler from running
}
// other code
});

关于jQuery 仅在第一次单击时防止默认,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21725886/

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