[英]Make whole Div clickable using jQuery
碼:
<style>
.mydiv {
border: 1px solid #00f;
cursor: pointer;
}
</style>
<div class="mydiv">blah blah blah.
<a href="http://examples.com">Examples link</a>
</div>
JS:
$(".mydiv").click(function(){
if($(this).find("a").length){
window.location.href = $(this).find("a:first").attr("href");
}
});
要么:
只需寫:
<a href="http://examples.com">
<div class="mydiv">blah blah blah.
Examples link
</div>
</a>
將錨元素移出div進行包裹
<a href="http://examples.com">
<div class="mydiv">blah blah blah</div>.
Examples link
</a>
$(document).on("click", ".mydiv", function(){
location.href = "http://examples.com";
}
如果您想使用jQuery來做到這一點,那么您正在尋找click函數。
$('.mydiv').click(function(){
location.href = 'example.com';
});
您可以簡單地使用HTML
<a href="http://examples.com">
<div class="yourDiv">blah blah blah.
Examples link
</div>
</a>
但
如果你想用jQuery做這樣的事情
$(document).ready(function(){
$(".yourDiv").on('click', function(){
//As an HTTP redirect (back button will not work )
window.location.replace("http://www.example.com");
});
});
根據要求使用JQuery:
$(document).ready(function() {
$('.mydiv').click(function() {
document.location.href='http://examples.com';
});
});
OFC,您可以(並且應該)讓瀏覽器按照Hiral的建議進行處理。
考慮到尚未被接受的其他答案,我假設您要使用<a>
元素的href
屬性不同的多個<div class="mydiv">
。
如果<a>
元素將始終是其父元素的最后一個子元素:
$(".mydiv").click(function(){
window.location.href = this.lastChild.href;
});
記住要刪除空格和<div>
的末尾。
JSFiddle: http : //jsfiddle.net/JAJuE/1/
如果<a>
元素將位於<div>
中的某處 (盡管不一定在末尾):
的HTML
<div class="mydiv">blah blah blah.
<a href="http://examples.com" class="mylink">Examples link</a>
</div>
JS
$(".mydiv").click(function(){
window.location.href = this.getElementsByClassName("mylink")[0].href;
});
JSFiddle: http : //jsfiddle.net/JAJuE/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.