简体   繁体   English

如何使用 jQuery 动态添加标签?

[英]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

html的前半部分 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:解释和逻辑:

  1. Identify li in #productlist and store it in listItems#productlist识别li并将其存储在listItems 中
  2. Loop through every listItems element via each loop通过每个循环遍历每个 listItems 元素
  3. In DOM element here called product , append the value of data property using jquery append() function在此处称为product 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM