我在 ajax 调用中返回了 html:
$.ajax({
url: '/get-html',
dataType: 'html',
success: function(html) {
html = $(html);
....
在 success 方法中,我希望在 html var 的容器 div 内找到 img 标签,并更改它的 alt 标签。
如果我这样做:
html.find('img').attr('alt', 'new alt');
我们更新了所有图像的替代信息。如何只指定容器 div 的 alt?我试过这个:
html.find('.container img').attr('alt', 'new alt');
但是它不起作用。
仅供引用,这是 ajax 调用中返回的 HTML 示例:
<div class="container">
<img src="" alt="PLEASE CHANGE THIS ALT">
</div>
<img src="" alt="LEAVE MY ALT ALONE">
<img src="" alt="LEAVE MY ALT ALONE">
最佳答案
试试这个 -
var html = '<div class="container"><img src="" alt="PLEASE CHANGE THIS ALT"/></div><img src="" alt="LEAVE MY ALT ALONE"/><img src="" alt="LEAVE MY ALT ALONE"/>';
//Print Your html Code before changing alt attr.
$('body').append(html);
$('body').append('<hr/>');
html = $(html);
//Check img inside .div and change attr
html.children('.container img').each(function() {
$(this).attr('alt', 'new alt');
//Log changed attr
console.log($(this).attr('alt'));
});
//Print Your html Code after changing alt attr.
$('body').append(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
关于javascript - 如何在另一个dom元素中找到一个dom元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39533206/