我正在使用ajax动态编写html代码,这意味着如果有人单击按钮,我会编写html代码来链接数字。
这是 html 代码。
<a class="show_figures" id="show_figures0" loop-id="0" href="javascript:showOrHidefigure(0);" style="text-decoration: none;"><b>Show figures</b></a>
这是插入 html 的 JavaScript 代码:
<script type='text/javascript'>
function showOrHidefigure(id_dummy){
var div = document.getElementById(id_dummy+'figures');
var dummy_id = $('#show_figures'+id_dummy).attr('loop-id') + 'figures'
var button = document.getElementById('show_figures'+id_dummy);
if(div.style.display == "block"){
div.style.display = "none";
button.innerHTML = "<b>Show figures</b>";
}
else{
div.style.display = "block";
if(!document.getElementById($('#show_figures'+id_dummy).attr('data-id')+'displayfigures')){
div.innerHTML = "Downloading Figures<br><br>"
button.innerHTML = "<b>Hide figures</b>";
$.ajax({
url: "/manage_figures",
type: "GET",
async: true,
cache: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: { arXiv_id: $('#show_figures'+id_dummy).attr('data-id')},
success: function(data) {
if(data.error){
console.log("error = ", data.error)
}
else{
document.getElementById(dummy_id).innerHTML = data.success
}
},
});
}
else{
button.innerHTML = "<b>Hide figures</b>";
}
}
}
</script>
“manage_figures”函数是一个在我的 Flask View 函数中调用的 Python 函数。但让我们假设它插入的代码如下所示
<div id="0displayfigures" value="1" style="display: inline-block">
<figure><a href="#"><img class="paper_img" src="/static/sourcefiles/image.png" alt="figure"/></a></figure>
</div>
我现在想要一个 JavaScript 函数,如果有人点击图像,该函数就会被触发
<script>
$(document).ready(function(){
$('.paper_img').click(function(){
console.log("test")
});
});
</script>
这个函数永远不会被触发?这可能与页面加载时包含类 pager_img 的 html 代码不存在有关?有人知道这个问题的解决方案吗? 谢谢 卡尔
最佳答案
由于您是动态创建 html 元素,因此您需要在附加 html 后注册点击事件处理程序。
$(document).on("click",".paper_img",function(){
alert("test");
});
关于javascript - 动态 html 和 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33702353/