Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

javascript - 为什么我用jQuery添加的新段落在点击时不起作用? [重复](Why do the new paragraphs I add with jQuery do nothing on click? [duplicate])

I have some paragraphs in my html as an example, and when I click on it, the JQuery click activates correctly and executes de function.(我在html中有一些段落作为示例,当我单击它时,JQuery单击会正确激活并执行功能。)

However, I have a button that adds new paragraphs to de body but the new ones do nothing on click and I don't know why:(但是,我有一个按钮,可以在主体中添加新段落,但是新段落在单击时不起作用,我也不知道为什么:) My html body(我的HTML正文) <h1> Test </h1> <input type="text" id="newP" value="New paragraph"> <button id="add"> Add </button> <p> Paragraph 1 </p> <p> Paragraph 2 </p> My js file(我的js文件) $(document).ready(function(){ $("p").click(function(){ console.log("Hello"); this.remove(); }); $("#add").click(function(){ $("#add").after("<p> " + $("#newP").val() + "</p>"); }); }); The 2 example paragraphs delete correctly and shows "Hello" but de new ones don't.(2个示例段落正确删除并显示“ Hello”,但新的段落则不显示。) I want to do something more complicated than just deleting them so I need to know why the function isn't working for them.(我想做的事情不仅仅是删除它们,所以我需要知道为什么该功能对他们不起作用。) (I must use JQuery)((我必须使用JQuery))   ask by Carmen Sirgo translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The reason is that you add new click listeners before adding new elements.(原因是您在添加新元素之前添加了新的Click侦听器。)

You can use the three-argument form of the click handler it will apply also to new elements added.(您可以使用点击处理程序的三参数形式,它也将应用于添加的新元素。) $(document.body).on('click', '#add', function(){ $(this).after("<p> " + $("#newP").val() + "</p>"); }); Another issue might be that you have multiple elements with the same id.(另一个问题可能是您有多个具有相同ID的元素。) You should give them css classes like add and then select for .add .(您应该给他们css类,例如add ,然后为.add选择。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...