循环以获取 href attr 并将作为变量作为 HTML 中的文本

loop to get the href attr and put as a variable as text in html

本文关键字:HTML 变量 文本 获取 href attr 循环      更新时间:2023-09-26

我让自己对DOM感到困惑。

我有这个 HTML:

<div class="my-list">
    <div class="name"></div>
    <div class="title"><a href="some_url"></a></div>
</div>
<div class="my-list">
    <div class="name"></div>
    <div class="title"><a href="some_url"></a></div>
</div>

而这个JavaScript:

var myList = $(".my-list");
for (var i=0;  i < myList.length; i++) {
    // what I want is at myList[i] to get the
    // $(".title a").attr("href") as a variable
    // and then put this variable as text
    // into the html of the $(".name") html
}

构建它的好方法是什么?

$(".my-list").each(function() {
    var element = $(this);
    var href = element.find('.title a').attr('href');
    element.find('.name').text(href);
});

这应该可以做到:

$('.my-list').each(function() {
    var self = $(this);
    $('.name',self).html( $('.title a', self).attr('href') );
});

这是它工作的示例

我对jquery来说不多,但这是一种确定的方法

$(".my-list").each(function(item){
    var divs = item.getElementsByTagName('div');
    for(var i in divs){
        if(typeof divs[i] != 'undefined' && divs[i].className == 'name'){
        divs[i].innerHTML = item.getElementsByTagName('a')[0].href;
        }
    }
});