我有一些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:
}
});
在我将
.menuItem
的文本发送到控制台的情况下,它似乎可以工作约99%。但是,在某些情况下,控制台会吐出空白。在这一点上,我认为有时实际上会单击实际的父元素.menuItem
,这时脚本会失败。有谁知道这可能是对的吗?我希望脚本能够处理发生的任何异常,但是首先我必须知道它是什么。提前致谢...
最佳答案
有时event.target
可以显示不同的元素。
我将其绑定到所需的元素,并使用$(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
,因为这就是我们要绑定的内容。关于jquery - jQuery导航栏单击失败。,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16976688/