简体   繁体   English

无法使用jQuery访问通过ajax加载的元素

[英]Can't access elements loaded via ajax using jQuery

I need to modify content loaded via ajax, but can't seem to access it. 我需要修改通过ajax加载的内容,但似乎无法访问它。 I don't have access to the js file that is doing the initial load so I need to write a separate function to change the content. 我无法访问正在执行初始加载的js文件,因此我需要编写一个单独的函数来更改内容。

The content needs to be modified automatically WITHOUT the user clicking or interacting with anything on the page. 无需用户单击或与页面上的任何内容进行交互,即可自动修改内容。

In the example below the 'news' div is hard coded and the 'article' divs are loaded via ajax. 在下面的示例中,'news'div是硬编码的,'article'div通过ajax加载。

HTML HTML

<div id="news">
<div class="article"><img src="headline1_small.jpg">
<div class="article"><img src="headline2_small.jpg">
<div class="article"><img src="headline3_small.jpg">
</div>

jQuery jQuery的

$(document).ready(function() {
  console.log( $("#news").html() );
});

Console 安慰

<div id="news">
</div>

How can I access the articles? 我怎样才能访问这些文章? I want to remove '_small' from the img src. 我想从img src中删除'_small'。

Thanks! 谢谢!

This should work: 这应该工作:

$(document).ajaxStop(function() {
    $("#news").find('img').attr("src", function(_, src){
        return src.replace('_small', '');
    });
});

How can I access the articles? 我怎样才能访问这些文章? I want to remove '_small' from the img src. 我想从img src中删除'_small'。

For example like this: 例如这样:

$('#news .article img').attr('src', function() {
    return this.src.replace('_small', '');
});

You can execute this code on AJAX successful completion 您可以在AJAX上成功完成此代码

$(document).ajaxSuccess(function() {
    // above code
});

You said the article div s are loaded through AJAX, seems that this script is running before they are loaded. 你说文章div是通过AJAX加载的,似乎这个脚本在加载之前就已经运行了。 Try putting this script after #news so all the content is already loaded when it is executed. 尝试在#news之后放置此脚本,以便在执行时已加载所有内容。

<div id="news">
<div class="article"><img src="headline1_small.jpg">
<div class="article"><img src="headline2_small.jpg">
<div class="article"><img src="headline3_small.jpg">
</div>

<script>
$(document).ready(function() {
  console.log( $("#news").html() );
});
</script>

To remove "_small" from src of the img tag, there is another way for that. 要从img标记的src中删除“_small”,还有另一种方法。 you dont need to get access to the html() -> innerHTML of the #news div. 你不需要访问#news div的html() - > innerHTML。

all you could do is get hold of the all the ".article" div's and then alter the img tag. 所有你能做的就是抓住所有的“.article”div,然后改变img标签。

$(".article img").each(function() {
   $(this).attr('src', $(this).attr('src').replace("_small", ""));
});

Thanks 谢谢

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

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