简体   繁体   English

元素加载到Ajax页面后,如何使用jQuery运行一些Javascript代码?

[英]how to run call some Javascript code with jQuery as soon as element loads to page by Ajax?

I'm trying to assign some attributes to some html tags as soon as they load to the page by Ajax, but I don't want to write any Javascript in my page. 我正在尝试将某些html标签由Ajax加载到页面时为它们分配一些属性,但是我不想在页面中编写任何Javascript。 foe example I have the the html like below:(remember that this comes via ajax, not on page load) 敌人的例子我有如下的html:(请记住,这是通过ajax来的,而不是页面加载时)

<div data-something="true">
 something here
</div>

and I want to have something like this which is saved to a .js file: (this doesn't work) 我想将这样的内容保存到.js文件中:(这不起作用)

$('body').on('load', '[data-something]', function(){  
       //do something 
});

but I do NOT want to have like this in one page : 但我不想在一页中有这样的内容:

<div data-something="true">
 something here
</div>

<script>
   $(function(){
        //do something
   });
</script>

is there anyway to do so? 反正有这样做吗? to trigger the event as soon as the element being loaded? 元素加载后立即触发事件?

Sure, put it in the success of the ajax call. 当然,把它放在ajax调用成功的地方。

$("someelemnt").load("somepage.html",function(){
    // do something.
});

do not use script tags on a page that you are loading via ajax, they'll usually get executed before the html is appended to the page. 不,你是通过AJAX加载页面上使用脚本标记,他们通常会得到之前的HTML被追加到页面执行。

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

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