each()类示例将Div Text追加到李
jQuery.each() class example Appending Div Text to Li
$EACH演示
总之,我正在获取"div class"的文本:并在控制台中打印。,我试图在"li>按钮"中添加相同的文本,但这并没有发生,不确定我哪里出了问题,
html:
<div class="productDescription">Red</div>
<div class="productDescription">Orange</div>
<div class="productDescription">Green</div>
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
JS:
//step - 1
$.each($('.productDescription'), function() {
var classTxt = $(this).text();
console.log(classTxt);
});
//outputs: Red Orange Green
//step - 2 now im trying to append the text to li
var liBtn = $(this).find('li').next('button');
console.log("Text of Button - "+ classTxt);
console.log(liBtn)
for (var i = liBtn.length; i >= 0; i++) {
liBtn[i]
};
感谢您的帮助,谢谢
您的代码中有几个错误。classTxt
是each
处理程序的上下文之外的undefined
,并且第二个this
引用window
对象而不是.productDescription
元素。
我建议使用.append()
方法的回调函数:
// cache the collection for better performance
var $p = $('.productDescription');
$('li button').append(function (index) {
return $p.eq(index).text();
});
http://jsfiddle.net/46yo7etz/
您也可以使用.text()
方法:
$('li button').text(function(index, currentTextContent) {
// using indices for selecting
// the corresponding `.productDescription` element
return currentTextContent + $p.eq(index).text();
});
请注意,小提琴的标记无效。li
元素应该是ul
/ol
元素的子元素。
$('li > button').text(function() {
return $('.productDescription').eq( $('li > button').index( this ) ).text();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="productDescription">Red</div>
<div class="productDescription">Orange</div>
<div class="productDescription">Green</div>
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
$("button").each(function(i){
$(this).text( $(".productDescription").eq(i).text() );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="productDescription">Red</div>
<div class="productDescription">Orange</div>
<div class="productDescription">Green</div>
<ul>
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
</ul>
http://jsfiddle.net/simply_simpy/uqmpvb7e/
相关文章:
- 添加文字和评论功能更新Div
- 如何将输入(type=text)从html表单传递到javascript函数
- 点击后隐藏潜水?(但如果Div是一面旗帜呢?)
- 使用JavaScript动态插入DIV的成本有多高
- DIV并排,位置不正确
- Div根据<选择>菜单
- 可以<脚本类型=“;text/javascript”>window.location=“/"</
- Href:当前DIV中的目标ID
- Onchange没有'不要显示或隐藏Div
- 绝对定位不适用于Javascript DIV
- 在Rails中更新Div,而不更改更新请求后的视图
- 在文本区域中使用jQuery.text()保持换行符
- how to convert html <div> to pdf
- 如何在不影响其他元素的情况下扩展DIV
- 用Javascript添加带有#text的tr元素
- 当用户按下回车键时,自动在text区域/text中插入消息
- 修正案'text'的元素
- 使用jQuery在页面上浮动DIV
- each()类示例将Div Text追加到李
- 从TEXT BOX中获得的url加载DIV中的图像