gpt4 book ai didi

jquery - 是否有可能阻止 HTML5 数据属性操作被 jQuery 触发?

转载 作者:太空宇宙 更新时间:2023-11-04 13:55:36 25 4
gpt4 key购买 nike

我问这个问题只是为了学习目的,因为我什至在写这篇文章之前就解决了这个问题,但也许你会指出一些对其他人有用的东西。

我正在使用 Twitter Bootstrap及其 modal lib这是我的代码的作用。我们打开一个模式,要求用户输入一些 json,然后用户按下“计算按钮”来计算数据,然后由于 data-dismiss 而关闭模式。

我只是想知道是否可以使用 jQuery、javascript 或其他东西来阻止由 html data-dismiss 属性触发的操作。

这是模式的 HMTL 代码:

<div class="modal hide fade" id="source_modal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>Manually insert the data</h3>
</div>
<div class="modal-body">
<textarea class="source_input">Insert your data here</textarea>
<div class="clear"></div>
<a href="#" class="btn action_clear">Clear</a>
</div>
<div class="modal-footer">
<a href="#" class="btn" data-dismiss="modal">Close</a>
<a class="btn btn-primary action_compute" data-dismiss="modal" href="#"><i class="icon-fire"></i> Compute</a>
</div>
</div>

注意最后一个按钮(计算按钮)有 data-dismiss="modal"

所以基本上,有一个 try catch 函数附加到 anchor 的 action_compute 类。

查看这段 jQuery 代码:

// compute graph with json input
$('.action_compute').on('click', function(event) {
try
{
var json = JSON.parse($('.source_input').val());
create_graph(json);
}
catch(err)
{
txt="There was an with your json data.\n";
txt+="Error description: " + err.message + "\n\n";
txt+="you can try to validate it with JSONLint. You may also leave the textarea blank for default behaviour";
alert(txt);
}
});

是否可以阻止data-dismiss触发的 Action ?

注意:

  • Twitter Bootstrap 提供了一个关闭模态的 jquery 方法,因此我删除了 data-dismiss 并使用 $('#upload_modal').modal('hide') 关闭了模态; 仅当我完成尝试时,它才会执行我想要的操作。
  • 将 jQuery event.preventDefault(); 放在 catch(err) jQuery 代码的第一行时不会停止关闭操作 ;)<

最佳答案

尝试添加一个监听器来阻止hide方法的执行。

$('.modal').one('hide', function (e) {e.preventDefault()});​​​​​​​​​​​​​​​

将它放在错误捕获部分。只要在调用 hide() 之前处理了点击事件,这就应该有效。

JSFiddle


既然你说这个问题是出于学习目的,我将在此处添加一些关于 Bootstrap 插件事件架构的额外信息。

许多 Bootstrap 插件都包含“之前”和“之后”事件。 “之前”事件(在本例中为隐藏)在执行相关方法的任何基本操作之前被触发并传播到 DOM 中。当执行返回到最初的触发方法时,发生的第一件事是检查操作是否已被取消:

if (e.isDefaultPrevented()) return

因此,任何调用 e.preventDefault() 的事件监听器都将有效地取消操作。正如您所期望的那样简单。

任何实现良好的触发事件的 jQuery 插件都应该具有此功能。

关于jquery - 是否有可能阻止 HTML5 数据属性操作被 jQuery 触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12014218/

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