简体   繁体   English

新增中 <li> 到 <ul> 基于使用jQuery的选择列表中的类别

[英]Adding <li> to an <ul> based on categories in a select list using jQuery

I have a bunch of <ul> on a page with <h2> just above each one that is a category name. 我在页面上有一堆<ul> ,其中<h2>刚好在每个类别名称的上方。 I am going to use PHP to populate the select list with each category name as an <option> , but what I need to know how to do is add a new <li> to each list based on the category name. 我将使用PHP使用每个类别名称作为<option>填充选择列表,但是我需要知道的操作是根据类别名称向每个列表添加一个新的<li> How can I accomplish this using jQuery? 如何使用jQuery完成此操作? I don't have any starter code. 我没有任何入门代码。

EDIT: Allow me to clarify. 编辑:请允许我澄清。 I have something like this: 我有这样的事情:

<form action="addSomething.php" method="post">
    <select name="categories">
        <option value="0">Pick one</option>
        <option value="1">Cat 1</option>
        <option value="2">Cat 2</option>
    </select>
    <input type="text" id="title" />
    <input type="text" id="URL" />
    <input type="submit" id="addNew">
</form>

<h2>Cat 1</h2>
<ul>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
</ul>

I want to be able to use the form above to select a category (the <h2> ), enter a name & URL, and then add it as a new <li> that corresponds to the selected category. 我希望能够使用上面的表格选择一个类别( <h2> ),输入名称和URL,然后将其添加为与所选类别相对应的新<li>

Without starter code, very hard to help. 没有入门代码,很难提供帮助。 Here's the general idea: 这是一般的想法:

<h2>Sample List</h2>
<ul class="someClass"></ul>

<select>
    <option value="someval">some option</option>
    <option value="someval2">some option</option>
</select>

And your JS can be: 您的JS可以是:

$("select").change(function() {
    if (this.value == "someval") {
        $("ul .someClass").append("<li>" + this.value + "</li>");
    }
});

Without any starter code, it's difficult to the exact solution you're looking for. 没有任何入门代码,很难找到您要的确切解决方案。

I don't understand exactly what your after, but this may help: 我不完全了解您的打算,但这可能会有所帮助:

$('h2.categoryName').each(function(){
    var name = $(this).text();
    $(this).next('ul').append('<li>' + name + '</li>');
});

Select each ul , get it's category, append an li . 选择每个ul ,获取其类别,然后附加一个li

html html

<h2 class="category">cat1</h2>
<ul></ul>
<h2 class="category">cat2</h2>
<ul></ul>
<h2 class="category">cat3</h2>
<ul></ul>

js js

$("ul").each(function(){
    var category = this.prev("h2").text();
    $("<li>" + category + "</li>").appendTo(this);
});

Here is a working fiddle . 这是工作中的小提琴 Of course you can put whatever text you want inside those lis elements. 当然,您可以在lis元素中放入所需的任何文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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