1
<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”,它将阻止用户转到链接位置。

谢谢。

4

2 回答 2

1

您只需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小写进行比较。

于 2013-03-20T17:33:28.947 回答
0

只需一行即可:

<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().

于 2013-03-20T17:30:51.427 回答