我一直试图弄清楚我的测试代码有什么问题。 preventDefault()
无效。{1}}警报即将到来,但正在跟踪链接。我的代码出了什么问题?
<html>
<head>
<title>JQuery Testing</title>
<script type="text/javascript" src="./jquery-1.10.2.min.js"></script>
</head>
<body>
<a href="#" class="Links1" id="link1" onclick="nav_bar($(this));">Nav Bar Link 0</a><br/>
<script type="text/javascript">
function nav_bar(thisObject){
var $objectID = thisObject.attr("id");
var $objectClass = thisObject.attr("class");
alert("A Link with Class : " + $objectClass + ", And ID Of : " + $objectID + " Was. Clicked!");
thisObject.preventDefault();
}
</script>
</body>
</html>
答案 0 :(得分:0)
由于您使用onclick
属性附加了活动,因此需要return false
来阻止默认行为:
<a href="#" class="Links1" id="link1" onclick="return nav_bar(this);">Nav Bar Link 0</a><br/>
function nav_bar(thisObject) {
var $el = $(this);
var $objectID = $el.attr("id");
var $objectClass = $el.attr("class");
alert("A Link with Class : " + $objectClass + ", And ID Of : " + $objectID + " Was. Clicked!");
return false;
}
或者,如果您通过jQuery附加事件,则可以使用preventDefault
,但请注意,需要在事件上调用它而不是引发事件的元素:
<a href="#" class="Links1" id="link1">Nav Bar Link 0</a><br/>
$('#link1').click(function(e)
e.preventDefault();
var $el = $(this);
var $objectID = $el.attr("id");
var $objectClass = $el.attr("class");
alert("A Link with Class : " + $objectClass + ", And ID Of : " + $objectID + " Was. Clicked!");
}
答案 1 :(得分:0)
方法preventDefauls属于event,不属于object。 我修改了你的代码:
function nav_bar(e, thisObject) {
var $objectID = thisObject.attr("id");
var $objectClass = thisObject.attr("class");
alert("A Link with Class : " + $objectClass + ", And ID Of : " + $objectID + " Was. Clicked!");
e.preventDefault();
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<title>JQuery Testing</title>
<script type="text/javascript" src="./jquery-1.10.2.min.js"></script>
</head>
<body>
<a href="#" class="Links1" id="link1" onclick="nav_bar(event, $(this));">Nav Bar Link 0</a><br/>
</body>
</html>
&#13;