[英]Adding a function to ajax dynamically created elements in vanilla js
Basically I am in the process of creating a movie info app using ajax, I have ran into a problem that I can't seem to solve. 基本上,我正在使用Ajax创建电影信息应用程序,但遇到了我似乎无法解决的问题。 Once I have created and ajax request I am then dynamically creating content and adding it to the page. 创建并提出Ajax请求后,我将动态创建内容并将其添加到页面中。 This is my dynamically created content. 这是我动态创建的内容。
output +=
`<div class="box">
<div class="box-image">
<img src="${val.Poster}" alt="${val.Title}">
</div>
<div class="box-body">
<h4 class="box-title">${val.Title}</h4>
<p class="year">${val.Year}</p>
<a href="#" class="modal-trigger" id="modalTrigger">Modal Trigger</a>
</div>
</div>`.
It is the anchor tag that is giving me problems, I want to add a function to it, so that I can open up a modal. 锚标签给我带来了问题,我想向它添加一个函数,以便我可以打开一个模态。 I would also like a way of preventing its default behaviour inside the function. 我还想要一种防止其在函数内的默认行为的方法。
You could add an event listener for clicks to the body document and select for the element you're creating as show below: 您可以为主体文档添加点击事件监听器,然后为要创建的元素进行选择,如下所示:
$("body").on('click', "a.modal-trigger", function(e) {
e.preventDefault();
$("#ajax").click(function() { $("#output").append( $("<a/>") .attr("id", "modalTrigger") .attr("class", "modal-trigger") .attr("href", "#") .text("modal") ); }); $("body").on('click', "a.modal-trigger", function(e) { e.preventDefault(); console.log('modal!'); $("#output").append("modal!"); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <button id="ajax"> Make Ajax Request </button> <div id="output"> </div> </body>
console.log('modal!'); console.log('modal!'); }); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.