[英]How do I make the entire div clickable using plain javascript?
我不需要用jQuery編寫此代碼,但是我對普通的javascript並不足夠了解。 克里斯·科耶爾(Chris Coyier) 對我在這里所說的話作了很好的解釋 。
我要轉換它的原因是因為我不需要為這一段代碼包含整個jQuery庫。 我可以使用普通的舊JavaScript保存該額外請求。
這是我要轉換的示例代碼:
$(document).ready(function() {
$(".featured").click(function(){
window.location=$(this).find("a").attr("href"); return false;
});
});
到目前為止,這是我想出的:
document.addEventListener("DOMContentLoaded", function() {
document.querySelectorAll("div.feature").click(function(){
window.location=$(this).find("a").setAttribute("href");
return false;
});
});
據我所知,這是不正確的一件事,是querySelectorAll
,它僅在查找div元素,對嗎? 另一件事是$(this)
,我不知道該如何將其轉換為普通的javascript。
假設...
querySelectorAll
支持,但您仍在使用它 addEventListener
僅適用於符合標准的瀏覽器 我相信你的意思是:
//get all a's inside divs that have class "featured"
var feat = document.querySelectorAll("div.featured a"),
featlen = feat.length,
i;
//loop through each
for(i=0;i<featlen;++i){
//add listeners to each
feat[i].addEventListener('click',function(){
window.location = this.href;
},false);
}
或者,您可以將<div>
包裝在<a>
。 不需要JS。 這是完全有效的HTML,盡管內聯元素不應包含block元素的規則,但瀏覽器仍可以按預期工作。 只要確保在<a>
上具有display:block
並調整其大小即可。
<a href="location">
<div> content </div>
</a>
您可以使用this.querySelectorAll(...)進行選擇:
IE8:
window.onload = function() {
// get all dom elements with class "feature"
var aFeatures = document.querySelectorAll(".feature");
// for each selected element
for (var i = 0; i < aFeatures.length; i++) {
// add click handler
aFeatures[i].onclick = function() {
// get href of first anchor in element and change location
window.location = this.querySelectorAll("a")[0].href;
return false;
};
}
};
IE9和其他當前瀏覽器:
document.addEventListener("DOMContentLoaded", function() {
// get all dom elements with class "feature"
var aFeatures = document.querySelectorAll(".feature");
// for each selected element
for (var i = 0; i < aFeatures.length; i++) {
// add click handler
aFeatures[i].addEventListener('click', function() {
// get href of first anchor in element and change location
window.location = this.querySelectorAll("a")[0].href;
return false;
});
}
});
===更新===
為了獲得IE7支持,您應該在之前添加以下(未經測試的)腳本(另請參見此處 ):
(function(d){d=document,a=d.styleSheets[0]||d.createStyleSheet();d.querySelectorAll=function(e){a.addRule(e,'f:b');for(var l=d.all,b=0,c=[],f=l.length;b<f;b++)l[b].currentStyle.f&&c.push(l[b]);a.removeRule(0);return c}})()
可能僅支持document.querySelectorAll
不支持element.querySelectorAll
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.