首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无法对使用jquery html()函数添加的'new html code‘执行js代码

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

Stack Overflow用户
提问于 2017-12-27 18:02:06
回答 1查看 33关注 0票数 2

我已经写了一些js代码。

代码结构如下:

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
<div id="jsHtmlCodeHere"> </div>

js文件:

代码语言:javascript
运行
复制
    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函数。

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-27 18:14:10

你必须使用一个监视器,因为你想要定位的元素还没有出现在页面上。您以父元素为目标,并设置与未来的子元素匹配的规则。

代码语言:javascript
运行
复制
$('#jsHtmlCodeHere').on('click', '#btn', function(){ alert('button clicked'); });
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47990074

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档