简体   繁体   中英

jQuery - preventDefault stops working after i add more code

I'm working with an image gallery. when I click on a photo, I would like nothing to happen. I used this code to accomplish that >>>

$('#imageGallery a').click(function(event){
event.preventDefault();     });

but all of a sudden, if I add this top line....

var $overlay = $("<div id = "overlay"></div>");

$('#imageGallery a').click(function(event){
    event.preventDefault();     
   });

...My code no longer works and the photo that I click goes to another page. Is there something I'm not doing or could this be a browser issue?

It's better to let jQuery create HTML elements for you. You had some typos in what you tried that resulted in malformed code. These are some methods of creating an element that are in decreasing order of human-error proneness:

Try using

var $overlay = $("<div id = 'overlay'></div>");

or

var $overlay = $("<div id = \"overlay\"></div>");

or

var $overlay = $("<div/>", {id: "overlay"});

or

var $overlay = $('<div/>').attr("id", "overlay");

to create new elements in the future.

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