简体   繁体   English

如何在不可点击的区域上点击DIV?

[英]How to make DIV clickable on non-clickable areas?

I have a <div> which contains a few links ( <a> tags) and other elements in it. 我有一个<div> ,其中包含一些链接( <a>标签)和其他元素。 I want to have the <div> behave like a button, which means whenever the user clicks on every part of it, it should navigate to some link. 我希望<div>表现得像一个按钮,这意味着每当用户点击它的每个部分时,它都应该导航到某个链接。 There are a few solutions like this one: Make a div into a link I can make it work with jQuery too, however, the problem is that I want the <a> tags in the <div> to work like before. 有一些像这样的解决方案: 将div设为链接我也可以使用jQuery,但是,问题是我希望<div><a>标签像以前一样工作。 I couldn't find any solution which makes this possible. 我找不到任何使这成为可能的解决方案。 How can I do this? 我怎样才能做到这一点?

$('#mydiv a').click(function(e) {
  e.stopPropagation();
});

Events bubble up, that's what they do. 事件泡沫起来,这就是他们所做的。 This is called propagation. 这称为传播。 Calling stopPropagation on the jQuery event object should prevent that event from bubbling up to your div that contains it. 在jQuery事件对象上调用stopPropagation应该可以防止该事件冒泡到包含它的div。

jQuery Docs here jQuery文档在这里

And since the event handler does not return false , then the browser default click handling for <a> tags will still be fired, which means the href is followed as normal. 并且由于事件处理程序不return false ,因此仍将触发<a>标记的浏览器默认单击处理,这意味着正常情况下将遵循href

Check out a working example here: http://jsfiddle.net/Squeegy/2phtM/ 在这里查看一个工作示例: http//jsfiddle.net/Squeegy/2phtM/

I think you need an event handler which determines which element triggered the click - something like this 我认为你需要一个事件处理程序来确定哪个元素触发了点击 - 就像这样

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
        <script>
            $(function() {
                $("#links").click(handler);
            })
            function handler(event) {

                var $target = $(event.target);
                if($target.is("#links")) {

                    window.location = "divlocation.htm"
                }
            }
        </script>
    </head>
    <body>
        <div id="links" style="background: yellow">
            <a href="test1.htm">link 1</a><br>
            <a href="test2.htm">link 2</a>
        </div>
    </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM