我有一些 HTML:
<div id="navigationBar" style="">
<div id="sheight" style="margin: 0px; padding: 0px; background-color: #dee5e8; width: 100%; height: 500px; overflow: hidden; position: relative;">
<div class="menuItem" style="height: 10px;">
</div>
<div id="selectedMenuItem" class="menuItem" style="">
<div class="tIcon" style="">
<img src="images/iconeducationtransparent.png" />
</div>
<div class="menuText" style="">
Education
</div>
</div>
<div class="menuItem">
<div class="tIcon">
<img src="images/iconfastcashtransparent.png" />
</div>
<div class="menuText">
Fast Cash
</div>
</div>
</div>
和一些 jQuery:
jQuery("#navigationBar").click(function(event) {
//console.log( jQuery(event.target).parents('.menuItem').html() );
var tt = jQuery(event.target).parents('.menuItem');
console.log( jQuery.trim(tt.children('.menuText').html()) );
var sNav = jQuery.trim(tt.children('.menuText').html());
switch(sNav)
{
case "Education":
alert("Eduction");
break;
case "Fast Cash":
alert("Fast Cash");
break;
case "Credit Cards":
alert("Credit Cards");
break;
case "Legal Help":
alert("Legal Help");
break;
case "New Car":
alert("New Car");
break;
case "Gov. Aid":
alert("Gov Aid");
break;
case "Health Care":
alert("Health Care");
break;
case "Debt Help":
alert("Debt Help");
break;
case "Auto Ins":
alert("Auto Ins");
break;
case "Credit Score":
alert("Credit Score");
break;
case "Paid Surveys":
alert("Paid Surveys");
break;
case "Specials":
alert("Specials");
break;
case "Debt Help":
alert("Deby Help");
break;
default:
}
});
它似乎在大约 99% 的时间里都能工作,在这种情况下,我将 .menuItem
的文本发送到控制台。然而,在某些情况下,控制台会出现空白。我认为,有时实际的父元素 .menuItem
实际上被单击,此时脚本失败。有谁知道这是否正确?我希望脚本能够处理发生的任何异常,但首先我必须知道它是什么。
提前致谢...
最佳答案
有时,event.target
可以显示不同的元素。
我会将其绑定(bind)到您想要的元素并使用 $(this)
,例如:
jQuery("#navigationBar .menuItem").click(function(event) {
var tt = $(this);
var sNav = jQuery.trim(tt.children('.menuText').text());
console.log(sNav);
alert(sNav);
});
这样 this
应该是 menuItem
因为这就是我们要绑定(bind)的内容。
关于jQuery 导航栏点击失败。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16976688/