循环以获取 href attr 并将作为变量作为 HTML 中的文本
loop to get the href attr and put as a variable as text in html
我让自己对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;
}
}
});
相关文章:
- 将html变量从Ajax传递到PHP
- 在JavaScript中使用HTML变量
- AngularJs - 从编译的 HTML/变量中获取一个字符串
- Node.js Express:重新访问注入到文件中.html变量
- PHP/HTML:将HTML变量保存在PHP会话变量中
- 如何从Ember.TextField的视图中切换HTML变量的值
- 使HTML变量可用于Rails渲染中的JavaScript
- 通过jquery从html变量中获取特定的标记
- 循环HTML变量并将span替换为content
- html变量到同一页面中的php变量
- 将HTML变量传递给Javascript
- 运行时在php HTML变量上运行javascript
- 在HTML变量中改变元素
- Javascript HTML变量表单入口
- 将Jquery/html变量链接到javascript
- Javascript/HTML变量未定义(全局变量)
- 将HTML变量传入Jquery
- 在JavaScript中使用HTML变量
- 使用javascript动态添加html变量
- JavaScript/HTML变量出现问题