防止点击事件内按钮上的jquery操作

时间:2015-04-30 22:12:38

标签: jquery

我有一个div,我已经添加了jquery点击事件,所以当你点击它时它会带你到一个网址。在同一个div里面我有一个删除条目的按钮。不幸的是,当我点击删除时我的.click事件会删除它,但它也会将我带到网址。如果单击按钮,如何防止.click事件被触发?

<script type="text/javascript">
    jQuery(document).ready(function($) {
        $(".clickable-row").click(function() {
            if ($(this).data("href") !== "") {
                window.open($(this).data("href"));
            }
        });
     });
</script>


<div class="box gallery clickable-row" id="item" data-href="www.amazon.com">
<div class="box-head clearfix">
    <div class="left">ghjlhgoig</div>
    <div class="right">$10</div>
</div>
<div class="box-content">
    <img src="/images/missing.gif">
    <form action="http://local.wishlist.com/lists/view/5" method="post" accept-charset="utf-8">
        <input type="hidden" name="itemId" value="19">
        <input type="submit" name="delete" value="Delete">
    </form>
</div>
</div>

为了清楚,如果我点击删除按钮,我希望它提交表格,而不是将我发送到网址。

3 个答案:

答案 0 :(得分:1)

点击甚至从删除按钮向上传播。有两种方法可以解决这个问题。

(1)检查事件是否从删除按钮冒出:

$(".clickable-row").click(function(event) {
    if (!$(event.target).is('input[name="delete"]')) {
        if ($(this).data("href") !== "") {
            window.open($(this).data("href"));
        }
    }
});

(2)阻止事件传播:

$('input[name="delete"]').click(function(event) {
    event.stopPropagation();
});

答案 1 :(得分:0)

从函数返回false。

<script type="text/javascript">
    jQuery(document).ready(function($) {
        $(".clickable-row").click(function() {
            if ($(this).data("href") !== "") {
                window.open($(this).data("href"));
            }
            return false;
        });
     });
</script>

或者将输入类型更改为“按钮”而不是“提交”,这将停止发布表单。

好的,我明白你现在在问什么。我认为您的选择如下:

1)在URL上添加重定向回到请求来自的页面。

2)或者使用AJAX调用发布。请参阅jQuery AJAX

3)发布到iframe(可能是最简单的选项)。

答案 2 :(得分:0)

编辑:您似乎想要将.clickable-row中的jQuery选择器更改为仅适用于打开新窗口的按钮的内容。

garryp是对的。您还可以使用jQuery方法event.preventDefault();

<script type="text/javascript">
    jQuery(document).ready(function($) {
        $(".clickable-row").click(function(event) {
            event.preventDefault();
            if ($(this).data("href") !== "") {
                window.open($(this).data("href"));
            }
        });
     });
</script>

请参阅jQuery here

相关问题