簡體   English   中英

如何使用preventDefault()(或類似方法)阻止鏈接停止工作?

[英]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


PS:如果要防止在用戶鍵入“ TextToBlock”( 區分大小寫 )時加載鏈接,請在測試功能中將“ texttoblock”更改為“ TextToBlock”,然后刪除.toLowerCase()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM