简体   繁体   中英

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>

I'd like it to be so that if someone typed in "TextToBlock" in the prompt box it would prevent the user from going to the link location.

Thanks.

You just need to pick up the event object from the click handler. (See fiddle 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>

Read more about Javascript event objects: http://javascript.info/tutorial/obtaining-event-object

Also, use === for strict comparisons. And also since you converted name .toLowerCase() you should be comparing it to texttoblock in lowercase .

All you need in just one line:

<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>

Demo: JSFiddle


PS: If you want to prevent loading the link when a user types "TextToBlock" ( case-sensitive ), in test function change "texttoblock" to "TextToBlock" and remove the .toLowerCase() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM