简体   繁体   English

无法从Ajax div调用JavaScript

[英]Can't call javascript from ajax div

I have some content loaded in my page using ajax. 我使用ajax在页面中加载了一些内容。 I want to run a JS function when some anchors are clicked. 单击某些锚点后,我想运行JS函数。 These anchors belongs to the code loaded using ajax. 这些锚点属于使用ajax加载的代码。 Both the ajax request and the JS function are located in a separate JS file, inside a jQuery(document).ready(function() { . ajax请求和JS函数都位于jQuery(document).ready(function() {

I have a few dozens functions in this JS file, and they're running fine, but this specific function is the only one called by code retrieved using ajax, and it is not working. 我在这个JS文件中有几十个函数,它们运行良好,但是这个特定的函数是使用ajax检索的代码调用的唯一函数,并且不起作用。 My code: 我的代码:

html main file: html主文件:

<!-- code -->
<div id="ajaxContentGoesHere">
<!-- content inserted here by ajax function -->
<td><a href="#" id="aLancamentoEdit<?php echo $lancamento['Lancamento']['lan_itid']; ?>">Editar</a></td>
</div>    
<script src="/js/myJS.js"></script>
</body> 

/js/myJS.js file: /js/myJS.js文件:

jQuery(document).ready(function() {
/*some other functions here*/
 $("[id^='aLancamentoEdit']").click(function(){
        console.log(1);
}
});

I tried to put the $("[id^='aLancamentoEdit']").click(function(){ inside the html main file, in a tag after the /js/myJS.js call. Didn't work. Also tried to change the selector to match my anchor class (I declared a class for this). No success either. Finally tried also to put a name in the function and call it on onclick="" inside the anchor. Failed again. 我试图将$("[id^='aLancamentoEdit']").click(function(){放在html主文件中,放在/js/myJS.js调用后的标记中。不起作用。尝试更改选择器以匹配我的锚定类(为此我声明了一个类)。也没有成功。最后还尝试在函数中放置一个名称,并在锚定内的onclick=""上调用它。再次失败。

What am I doing wrong? 我究竟做错了什么?

Since the element by id starting with 'aLancamentoEdit' is dynamically added by ajax, you need to bind click handler to parent: 由于以'aLancamentoEdit'开头的id为id的元素是由ajax动态添加的,因此您需要将click handler绑定到parent:

$('#ajaxContentGoesHere').on('click', "[id^='aLancamentoEdit']", function() {
   console.log(1);
});

Use .on() for dynamic element events (ajax content in your case). .on()用于动态元素事件(在您的情况下为ajax内容)。 Try: 尝试:

jQuery(document).ready(function() {
/*some other functions here*/
 $("#ajaxContentGoesHere").on("click","[id^='aLancamentoEdit']",function(){
        console.log(1);
}
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM