繁体   English   中英

如何使div可点击?

[英]How to make div clickable?

我想使这个div可以点击并且想要使用内部<a>相同href并且想要在<a>内部保持链接(因此如果禁用JS则可以访问链接)。

<div id="example">

<p> some text </p>

<img src="example.jpg />

<a href="http://stackoverflow.com"> link </link>

</div>

我的意思是我需要这样的。

<div id="example" href="http://stackoverflow.com">

<p> some text </p>

<img src="example.jpg />

<a href="http://stackoverflow.com"> link </link>

</div>

这样的事应该做

$('#example').click(function() {
  window.location.href = $('a', this).attr('href');
});

我还不能回复上面的对话,因为我是新来的,但我只是想说你不需要从这个函数return false 这样做是为了防止事件的默认行为发生(在单击div的情况下是什么),并阻止事件传播到DOM层次结构中的下一个元素。

在这种情况下,这些都不太可能是必要的。 此外,如果您确实需要这些行为,您可以单独获取它们,并且更清楚地如下:

// note that the function will be passed an event object as
// its first argument.
$('#example').click(function(event) { 
  event.preventDefault(); // the first effect
  event.stopPropagation(); // the second

  window.location.href = $('a', this).attr('href');
});

同样,我不认为在这种情况下这两种方法都是必要的,但重要的是要了解它们的工作原理,因为您经常需要其中一种或两种。

<html>  
  <body>
    <div onclick="window.location.href = this.getElementsByTagName('a')[0].href;">
      <p>some text</p>      
      <a href="http://www.google.co.in/">link</a>
    </div>
  </body>
</html>

以上答案都被我接受了。 通常你可以通过css对“div”产生相同甚至更大的效果而不是“a”。 并且您可以添加js函数来显示事件发生时的css更改,如Click。 也许是这样的:DIV.onclick = function(){在这里改变目标dom对象css}。然后当事件发生时,你会看到效果。 如果你想将href改为另一个。 写像location.href =“http://www.target.com”的js; 它会对你有用。

暂无
暂无

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

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