我有以下 div:
<div class="panel-heading">
<h3 class="panel-title"><a href="#">Test Title</a> <small>Aug 24, 2013</small></h3>
</div>
我想这样做,以便当用户单击.panel-heading
(该 div 的任何部分)时,它将打开链接到Test Title
. 在这种情况下,它应该打开#
. 我如何使用 jQuery 做到这一点?
$('.panel-heading').click(function(){
window.location.href = $(this).find('a').attr('href');
});
personally, in a situation like this, assuming you are in control of the HTML, I would write it like so:
HTML:
<div class="panel-heading" data-href="#">
<h3 class="panel-title">Test Title <small>Aug 24, 2013</small></h3>
</div>
script:
$('.panel-heading').click(function() {
if ($(this).data('href')) {
location.href = $(this).data('href');
}
});
Then you could style the HTML however you like, adding any kind of text decoration you wish. Of course, this approach has it's advantages and drawbacks, the advantages being you can globalize this function by using a generic class such as 'link', and have the click event attached to a jQuery selector that selects that class, so that you can have multiple elements in your HTML code that are controlled by one function. The most obvious drawback to this approach is that the browser functionality of previewing an anchor link is disabled, but of course you could add the title attribute to give an alternative view of the same information.
我个人已经通过像这样锚定整个 div 来解决这个问题
<a href="#"><h3 class="panel-title">Test Title<small>Aug 24, 2013</small></h3></a>
根据您的情况,您最好<a>
也在那里包含日期,并使用 display:block 对其进行样式设置,以便它填充 div。那么就不需要JS了。
<div class="panel-heading">
<h3 class="panel-title"><a href="#">Test Title <small>Aug 24, 2013</small></a></h3>
</div>
.panel-heading a {display:block;}
试试这样:
$('.panel-heading').click(function(){
element.find(">:first-child").click();
});
最好只用链接包装 div:
<a href="#">
<div class="panel-heading">
<h3 class="panel-title">Test Title <small>Aug 24, 2013</small></h3>
</div>
</a>
但是,如果您必须使用 javascript...
$( ".panel-heading" ).on( "click", function() {
var tgt = $( this ),
href = $( "a", tgt ).attr( "href" );
window.location.href = href;
});