简体   繁体   中英

jQuery onclick event using javascript:void(0)

I'm trying to modify a link so it shows javascript:void(0) when the link is hovered over.

$(document).ready(function(){
   if( $('.loggedinusername').length )  {
$("div#moresearches ul").append("<li id='xxx'><a href='https://exmample.org'>Link</li>");
   }
   });

I've tried:

$(document).ready(function(){
   if( $('.loggedinusername').length )  {
$("div#moresearches ul").append("<li id='xxx'><a href='javascript:void(0)' onclick="location.href='https://example.org'>Link</li>");
   }
   });

But it doesn't seem to work. I noticed that there are issues with the apostrophes but I can't seem to sort out how to make them work. Let me know if you need any more clarification and I'd happily provide it. Any help would be appreciated.

Here is a cleaner way to do it. Anyway this is a completely wrong approach for security. Put the link in your html this way.

<li id='xxx'><a href="javasctipt:void(0)" data-url="https://exmample.org" class="no-show-url" >Link</li>

Then in your document ready you just do:

$(document).ready(function(){
   if( $('.loggedinusername').length ){
       //I don't want you to see and follow the link
       $(".no-show-url").click(function(){
           e.preventDefault(); //not strictly necessary but reinforce the behaviour
       });
   }else{
       //you don't see but can follow the link
       var url = $(".no-show-url").data("url");
       window.location(url);
   }
});

You will just need to escape the double quotes like:

onclick=\"location.href='https://example.org'\"
     ___^___                              ___^___

Otherwise, it is messing up the generated output and redirection doesn't work.

Demo Here:

 $("div#moresearches ul").append("<li id='xxx'><a href='javascript:void(0)' onclick=\"location.href='https://example.org'\">Link</li>");
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="moresearches"> <ul></ul> </div>

You can add a tooltip using the title attribute over your anchor tag, which will appear whenever the mouse hovers over it.

<li id='xxx'><a title="javasctipt:void(0)" href="https://exmample.org" >Click here </li>

I think this is the most optimized way of doing it.

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