[英]How to block a stop a link from working using preventDefault() (or something similar)?
<script>
function test() {
var name=prompt ("Some question / text")
if (name.toLowerCase()=="TextToBlock") {
alert ("text");
name.preventDefault();
}
else {
}
}
</script>
<body>
< a id="link" onclick="test()" href="http://www.example.com">Text</a>
</body>
我希望這樣,如果有人在提示框中鍵入“ TextToBlock”,它將阻止用戶進入鏈接位置。
謝謝。
您只需要從點擊處理程序中拾取event
對象。 (請參見小提琴http://jsfiddle.net/amyamy86/pJvZd/ )
function test(event) {
event = event || window.event;
var name = prompt("Some question / text")
if (name.toLowerCase() === "texttoblock") {
alert("text");
event.preventDefault(); // block link from working
} else {
}
};
<body>
<a id="link" onclick="test()" href="http://www.example.com">Text</a>
</body>
閱讀有關Javascript事件對象的更多信息: http : //javascript.info/tutorial/obtaining-event-object
另外,請使用===
進行嚴格比較。 另外,由於您已轉換名稱.toLowerCase()
,因此應將其與小寫的 texttoblock
進行比較。
您只需一行就可以滿足所有要求:
<script>
function test() {
return "texttoblock" === prompt("Some question / text").toLowerCase() ? (window.event.preventDefault(), alert("text"), !1) : !0
};
</script>
<body>
<a id="link" onclick="test()" href="http://www.example.com">Text</a>
</body>
演示: JSFiddle
.toLowerCase()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.