[英]How do I add labels dynamically using jQuery?
I do not know how to use jQuery at all and I really need some help.我根本不知道如何使用 jQuery,我真的需要一些帮助。 Here is what I'm trying to do...
这是我正在尝试做的...
I need to add those labels next to those without any hard-coding the text in the HTML.我需要在那些没有对 HTML 中的文本进行任何硬编码的标签旁边添加这些标签。 I'm very new to jQuery and would really love some help.
我对 jQuery 很陌生,真的很想得到一些帮助。
HTML HTML
jQuery (This is from a tutorial) jQuery(这是来自教程)
$("document").ready(function(){
$("body").append("<p>JSQuery Hello World");
});
window.addEventListener("DOMContentLoaded", function(evt) {
var elem = document.getElementsByTagName("body")[0];
var para = document.createElement("p");
var text = document.createTextNode("This is regular JS");
para.appendChild(text);
elem.appendChild(para);
});
Solution code解决方案代码
<script src="your jquery src"></script>
<ul id="productList">
<li data-type="family">Coffee</li>
<li data-type="child">Tea</li>
<li data-type="family">Milk</li>
<li data-type="child">Milk</li>
<li data-type="family">Milk</li>
</ul>
<script>
$(document).ready(function () {
var listItems = $("#productList li");
listItems.each(function (idx, li) {
var product = $(li);
product.append(" - <b> ("+product.attr('data-type')+") </b>");
// and the rest of your code
});
});
</script>
Explanation & logic:解释和逻辑:
li
in #productlist
and store it in listItems#productlist
识别li
并将其存储在listItems 中product
, append the value of data property using jquery append()
functionproduct
DOM 元素中,使用 jquery append()
函数append()
data 属性的值Please note: if no data attribute is defined, undefined will be printed instead of value.
请注意:如果没有定义数据属性,将打印 undefined 而不是 value。 To resolve this bug you can add an if condition in each loop and then append.
要解决此错误,您可以在每个循环中添加一个 if 条件,然后追加。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.