简体   繁体   English

在Vanilla JS中向Ajax动态创建的元素添加函数

[英]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.

相关问题 使用 vanilla JS 向动态创建的 html 元素添加点击事件 - Adding a click event to a dynamically created html element using vanilla JS 在嵌套循环 vanilla JS 中动态添加和删除元素 - adding and removing elements dynamically within nested loops vanilla JS 使用Vanilla JS向表中动态添加内容 - Dynamically adding content to table using Vanilla JS 动态添加样式到香草js中的元素不起作用 - Adding styles dynamically to element in vanilla js not working 为动态创建的元素/ JS / jQuery添加唯一的类名 - Adding unique class name to dynamically created elements/ JS / jQuery 在IE8中通过JS将占位符添加到动态创建的元素中 - Adding placeholder to dynamically created elements by JS in IE8 使用 JS 或 Jquery 向动态创建的元素添加事件 - adding events to dynamically created elements using JS or Jquery 通过单击来删除使用香草JavaScript动态创建的元素 - Removing dynamically created elements with vanilla JavaScript by clicking on them 事件委托/使用 Vanilla JavaScript 将事件附加到动态创建的元素 - Event Delegation / Attaching events to dynamically created elements using Vanilla JavaScript 如何使用香草javascript将数组值返回到动态创建的元素 - how to return an array value to dynamically created elements with vanilla javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM