简体   繁体   English

jQuery-PreventDefault在我添加更多代码后停止工作

[英]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. 最好让jQuery为您创建HTML元素。 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. 在未来创造新的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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