event.preventDefault() 不起作用

发布于 2025-01-08 06:29:29 字数 2193 浏览 0 评论 0原文

我在使用 Telerik Grid 的视图中有这行代码:

      columns.Bound(o => o.URI).Width(10).Sortable(false)
                .ClientTemplate("<A class='btnGrid' id=source<#= ID #> onclick=GridSelection.addItem('<#= ID #>') >Add</A>").Title("").Width(50);

GridSelection addItem 和disableSelected 函数的 JS 代码:

  GridSelection = {
      addItem: function (value) {

         var anchorOption = $("a[id=source" + value + "]");

         anchorOption.click(function (e) { // variable name changed from "event"
               e.preventDefault();
               return false;    // as suggested by mr. Hamdi
               });

         anchorOption.fadeTo("slow", .5);

         GridSelection.disableSelected(anchorOption, true);

         var data = $("#GridSource").data('tGrid').data;
         var selectedObject;
         for (var item in data) {
            if (data[item].ID == value) {
               selectedObject = data[item];
               break;
            }
         }

          var grid = $("#GridSelected").data('tGrid');
          var newData = $("#GridSelected").data('tGrid').dataSource._data;
          newData.push(selectedObject);
          grid.dataBind(newData);
          grid.sort("");
          anchorOption.fadeTo("slow", .5);
      },

      disableSelected: function (element, disable) {
              //false on IEs 6, 7 and 8
              if (!$.support.leadingWhitespace) {
                  if (disable) {
                      $(element).attr('disabled', 'disabled');
                  } else {
                      $(element).removeAttr('disabled');
                  }
              }
     },
         // other GridSelection subfunctions here...

当我在 IE 中运行 MVC3 Web 应用程序时,由于 GridSelection.disableSelected 函数,它运行良好,但在 ChromeMozilla Firefox 中,event.preventDefault(); 不起作用。即使用户已经将数据项添加到锚链接中,锚链接仍然会添加数据项。

在被阻止的 GridSelection.addItem 函数中使用 preventDefault 方法是否可以?

preventDefault 阻止了哪个属性,是 href 还是 onclick

这有什么问题吗? 我该如何修复这个错误? 有谁可以帮忙吗?

i have this line of code in my view using the Telerik Grid:

      columns.Bound(o => o.URI).Width(10).Sortable(false)
                .ClientTemplate("<A class='btnGrid' id=source<#= ID #> onclick=GridSelection.addItem('<#= ID #>') >Add</A>").Title("").Width(50);

the GridSelection addItem and disableSelected functions' JS codes:

  GridSelection = {
      addItem: function (value) {

         var anchorOption = $("a[id=source" + value + "]");

         anchorOption.click(function (e) { // variable name changed from "event"
               e.preventDefault();
               return false;    // as suggested by mr. Hamdi
               });

         anchorOption.fadeTo("slow", .5);

         GridSelection.disableSelected(anchorOption, true);

         var data = $("#GridSource").data('tGrid').data;
         var selectedObject;
         for (var item in data) {
            if (data[item].ID == value) {
               selectedObject = data[item];
               break;
            }
         }

          var grid = $("#GridSelected").data('tGrid');
          var newData = $("#GridSelected").data('tGrid').dataSource._data;
          newData.push(selectedObject);
          grid.dataBind(newData);
          grid.sort("");
          anchorOption.fadeTo("slow", .5);
      },

      disableSelected: function (element, disable) {
              //false on IEs 6, 7 and 8
              if (!$.support.leadingWhitespace) {
                  if (disable) {
                      $(element).attr('disabled', 'disabled');
                  } else {
                      $(element).removeAttr('disabled');
                  }
              }
     },
         // other GridSelection subfunctions here...

As I run the MVC3 web app in IE, it runs well because of the GridSelection.disableSelected function, but in Chrome and Mozilla Firefox, the event.preventDefault(); doesn't work. The anchor link still adds the data item even after the user has already added it there.

Is it OK having the preventDefault method inside the GridSelection.addItemfunction that was being prevented?

Which attribute is being prevented by the preventDefault , is it the href or is it the onclick?

What wrong with this?
How can I fix this bug?
Anyone who can help?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

南城旧梦 2025-01-15 06:29:29

您的链接的标记有一个内联点击处理程序,但没有 href

<A class='btnGrid' id=source<#= ID #> onclick=GridSelection.verify('<#= ID #>') >Add</A>

您试图阻止的是 GridSelection.verify(),您应该注意:

  1. 如果 内联点击处理程序可能在您的其他事件处理程序之前被调用,这意味着从您的其他处理程序中取消它为时已晚,并且在任何情况下
  2. e.preventDefault() 都不会不阻止其他处理程序运行,它会停止事件的默认操作,该事件对于链接来说是导航到 href 属性中指定的 url。并且您没有指定 href

如果您想在同一元素上为同一事件拥有多个处理程序,则应使用 jQuery 按照您希望调用它们的顺序将它们全部分配,然后使用 event.stopImmediatePropagation() 方法 在其中一个处理程序中(如果您想停止其余处理程序)从跑步。

鉴于您没有显示您想要阻止的部分代码,我不知道如何将其放入您所显示的代码中,但一般原则是:

<a id="myLink" href="someURL">My link</a>

<script>
$("#myLink").click(function(e) {
    // some processing
    if (someCondition)
       e.stopImmediatePropagation();
    // some other processing
});

$("#myLink").click(function(e) {
    // some processing
});
</script>

话虽如此,如果 .verify () 函数调用您的 .addItem() 函数,您的目的是阻止未来点击事件在同一链接上工作,因为第一次点击应该验证/add 然后你不想再添加了,然后在您的 .addItem() 函数中执行如下操作:

anchorOption.removeAttr("onclick");
// or
anchorOption[0].onclick = null;

The markup for your link has an inline click handler and no href:

<A class='btnGrid' id=source<#= ID #> onclick=GridSelection.verify('<#= ID #>') >Add</A>

If it is the GridSelection.verify() that you're trying to prevent you should note that:

  1. The inline click handler is probably being called before your other event handler which means it is too late to cancel it from your other handler, and in any case
  2. e.preventDefault() doesn't stop other handlers from running, it stops the default action for the event which for a link is to navigate to the url specified in the href attribute. And you don't specify an href.

If you want to have multiple handlers for the same event on the same element you should assign them all with jQuery in the order you want them to be called, and then use the event.stopImmediatePropagation() method within one of the handlers if you want to stop the rest of them from running.

I don't know how to fit that within the code you've shown given that you don't show part of the code you want to prevent, but the general principle is:

<a id="myLink" href="someURL">My link</a>

<script>
$("#myLink").click(function(e) {
    // some processing
    if (someCondition)
       e.stopImmediatePropagation();
    // some other processing
});

$("#myLink").click(function(e) {
    // some processing
});
</script>

Having said all that, if the .verify() function calls your .addItem() function and it is your intention to prevent future click events from working on the same link because the first click should verify/add and then you don't want to be able to add again, then within your .addItem() function do something like this:

anchorOption.removeAttr("onclick");
// or
anchorOption[0].onclick = null;
木槿暧夏七纪年 2025-01-15 06:29:29

您是否尝试过添加 return false; 而不是 event.preventDefault();

Have you tried adding return false; instead of event.preventDefault();

暖伴 2025-01-15 06:29:29

您是否尝试过重命名事件变量?你可以说我疯了,但我似乎记得遇到问题,只需尝试 function(e) {e.preventDefault();} 看看会发生什么

Have you tried renaming the event variable? call me crazy but I seem to recall having issues just try function(e) {e.preventDefault();} and see what happens

献世佛 2025-01-15 06:29:29

香草(没有 jQuery)的魔力是 stopPropagation。为了阻止任何可能的事件冒泡,您通常需要将两者配对。组合后,您可以实现以下两个目标:

  1. 防止默认环境/浏览器行为 (preventDefault) 和
  2. 不触发附加到 DOM 祖先的任何其他脚本 (stopPropagation)。

制定最终解决方案:

evt.preventDefault();
evt.stopPropagation();

已更详细地讨论了两者之间的区别这里,以及许多其他地方。

The magic sauce in vanilla (without jQuery) is stopPropagation. In order to stop any possible event bubbling, you usually want to pair the two. When combined, you achieve both:

  1. Prevent default environment/browser behavior (preventDefault) and
  2. Not triggering any other scripts attached to DOM ancestors (stopPropagation).

Making the final solution:

evt.preventDefault();
evt.stopPropagation();

The difference between the two has been discussed in greater detail here, and many other places.

飘然心甜 2025-01-15 06:29:29

如果锚点有一个id,请使用id选择器而不是将其用作属性选择器。

更改

$("a[id=source" + value + "]")

$("#source" + value)

我并不是说这是问题所在,但您可以尝试更改此设置。

更新:

event.preventDefault() 阻止浏览器跟踪锚元素的 href 属性中设置的链接。它不会阻止或停止click 事件。

If the anchor has an id use the id selector instead of using it as attribute selector.

Change

$("a[id=source" + value + "]")

To

$("#source" + value)

I am not saying this is the issue but you can try changing this.

Update:

event.preventDefault() stops the browser to follow the link set into href attribute of anchor element. It will not prevent or stop the click event.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文