无法在使用jquery html()函数添加的'new html code'上执行js代码

时间:2017-12-27 10:02:06

标签: javascript jquery html ajax

我写了一些js代码。

代码的结构如下:

1. i load the page with basic html and js;
2. i make an ajax call (to php) and get the json variable;
3. i output the variable with some html code via jquery html
4. i would like to add  an extra code that is relevant to the html code i output on stage number '3'. i write the code with the general
js code in stage number '1' and it does not execute. it works oblt
when i add the js code to the variable containing html code on stage
'3'.

这是代码结构:

HTML:

<div id="jsHtmlCodeHere"> </div>

js file:

    function getVeriableFromAjax(){
//ajax code is here
//successful ajax reuqest 200
    return 'hello world';
}

var ajaxData=getVeriableFromAjax();
var htmlCode="<button type='button' id='btn'>"+ajaxData+"</button>";

/*htmlCode += "<script>$('#btn').click(function(){alert('button clicked');});</script>"; this alert code works in my project only when i'm adding it to the 'htmlCode' variable.*/

$('#jsHtmlCodeHere').html(htmlCode);

$('#btn').click(function(){
    alert('button clicked');
});//this function does not execute in my code for some reason.

有谁知道这是什么问题?我想在第1阶段写下点击功能。

谢谢!

1 个答案:

答案 0 :(得分:1)

您必须使用观察者,因为您要定位的元素尚未在页面上。您定位父元素并设置规则以匹配未来的子元素。

$('#jsHtmlCodeHere').on('click', '#btn', function(){ alert('button clicked'); });