简体   繁体   English

是否可以迭代Bootstrap列表?

[英]Is it possible to iterate over a Bootstrap list?

I have a Twitter Bootstrap list with a variable number of elements (in fact there are two lists with draggable and droppable elements done with Sortable.js ). 我有一个Twitter Bootstrap列表,其中包含可变数量的元素(实际上有两个列表,其中包含使用Sortable.js完成的可拖动和可放置元素)。

At some point, I want to iterate those lists elements in order to get a data atribute from each list entry. 在某些时候,我想迭代这些列表元素,以便从每个列表条目中获取数据属性 This is how my list looks like at HTML: 这就是我的HTML列表:

       <div class="panel-body">
            <ul id="main_list" class="list-group">
                <li id="opt1" href="#" class="list-group-item" data_value="1">Opt 1</li>
                <li id="opt2" href="#" class="list-group-item" data_value="2">Opt 2</li>
                <li id="opt3" href="#" class="list-group-item" data_value="3">Opt 3</li>
            </ul>
        </div>

Is this even possible to achieve, or am I thinking too object oriented? 这甚至可能实现,还是我认为太面向对象? If not, how should I rethink this task? 如果没有,我该如何重新考虑这项任务?

You can put your specific information like 你可以把你的具体信息

<li id="opt3" href="#" class="list-group-item" data-value="3">Opt 3</li>

and get that easily with jquery: 并使用jquery轻松获得:

$("#opt3").data("value")

But the semantic way to do that is with "-" instead of "_". 但是这样做的语义方式是“ - ”而不是“_”。


To iterate your list, you can do: 要迭代列表,您可以执行以下操作:

 $("#main_list li").each(function(){ var itemValue = $(this).data('id'); var itemName = $(this).data('name'); alert(itemValue+" - " +itemName); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="panel-body"> <ul id="main_list" class="list-group"> <li id="opt1" href="#" class="list-group-item" data-name="customname1" data-id="1">Opt 1</li> <li id="opt2" href="#" class="list-group-item" data-name="customname2" data-id="2">Opt 2</li> </ul> </div> 

Thiago's answer is totally valid, and if jQuery is already used then it should be the accepted answer. Thiago的答案是完全有效的,如果已经使用了jQuery,那么它应该是公认的答案。 But for the sake of it here is a solution in plain js: 但是为了它,这里是一个简单的js解决方案:

var elements = document.getElementById('main_list').children,
    maxElements = elements.length,
    counter = 0,
    tmpAttribute;

for (; counter < maxElements; counter++) {
    tmpAttribute = elements[counter].getAttribute('data_value');
    // whatever you need to do with tmpAttribute
}

You could wrap that in a function and call it on click for example. 你可以将它包装在一个函数中并在点击时调用它。 Here is a demo to see it in action: http://jsfiddle.net/Lzcbzq7x/1/ 这是一个演示,看看它在行动: http//jsfiddle.net/Lzcbzq7x/1/

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

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