我已经写了一些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文件:
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中编写click函数。
谢谢!
发布于 2017-12-27 18:14:10
你必须使用一个监视器,因为你想要定位的元素还没有出现在页面上。您以父元素为目标,并设置与未来的子元素匹配的规则。
$('#jsHtmlCodeHere').on('click', '#btn', function(){ alert('button clicked'); });
https://stackoverflow.com/questions/47990074
复制相似问题