在使用 ajax 动态添加的 DOM 元素的点击上调用 JavaScript 函数

calling javascript function on onclick of dynamically added dom element using ajax

本文关键字:调用 函数 JavaScript 元素 DOM ajax 动态 添加      更新时间:2023-09-26
嗨,我

很久以前就遇到了这个问题,我浪费了很多时间来找出问题所在。让我讲讲这个场景。假设我有一个 html 页面,因为我有几个元素已经在页面中,并且我正在使用 ajax 调用动态添加一些元素。在向页面添加新项目时,我得到了这样的场景,例如我需要为其中一个元素添加一个 onClick 函数调用以及一个对象作为参数。但是当我在 jquery 中添加函数时,函数被调用,但我在函数中得到的对象与我传入的对象不同。对象正在转换为字符串而不是对象。

<html>
<body>
.
.
.
... Some html code....
.
.
.
.
<div onclick="function1();"> </div>
.
.
<div id="dynamicElement"> </div>
.
.
</body>
<script type="text/javascript">
function function1(){
   .
   .
   $.ajax(){
    success(obj):{ 
          $("#dynamicElement").empty().append('<input id="iButton" type="button" onclick="function2('+obj+')">')
        }
   }
}
</script>
<script type="text/javascript">
 function2(obj){
   //Here When I try to manipulate with this object. I was actually not abt to do.
   // this is because of the object u add in dynamic elements will get converted to string instead of ibject.
 }
</script>
</html>

这个问题的解决方案是。我们甚至需要在外部添加 onclick,而不是在添加元素本身时指定它。

上述示例的解决方案:在 Ajax 中调用只需添加按钮元素。

$.ajax(){
    success(obj):{ 
          $("#dynamicElement").empty().append('<input id="iButton" type="button">');
      $("#iButton").onClick({
          function2(obj);
         });
        }
   }

现在它完美运行。