简体   繁体   中英

Get all li data-val in an ul

I can't get the data-val of a li when it has a link inside, could you help me to fix it?

li example:

<li data-val="Lima 2">Lima [T:19ºC H:82%]<a href="#" onclick="if(confirm('Remover?')){parentNode.parentNode.removeChild(parentNode)}"><span style="float:right;"><b>[X]</b></span></a>
</li>

Javascript

$("#cup").on("click", function () {
$('.clista').each(function () {
    var cidades = [];
    var cidade = '';
    $(this).find('li').each(function () {
        var current = $(this);
        if (current.children().size() > 0) {
            return true;
        }
        cidade += $(this).attr('data-val');
        alert(cidade);
    });
    cidades.push(cidade);
});

});

Could you check the script: http://jsfiddle.net/fabiobraglin/rcheaowx/8/

Tks a lot!

Since you have put an if block which returns true if li has children. I don't know what are you trying to accomplish by doing so. However, that if check becomes true and function exits by returning true. If you remove that return statement or remove complete if block, your update function will work fine. Try this. Hope it helps.

try this:

   $("#cup").on("click", function () {
        var   cidades = new Array();
        $('.clista li').each(function () {
         cidades.push($(this).data('val'));
            });

        alert(cidades);
        });

http://jsfiddle.net/rcheaowx/9/

You should write your alert outside of the each function. And you shouldn't check for children, that's why you don;t get the result you want.

$('.clista').each(function () {
    var cidades = [];
    var cidade = '';
    $(this).find('li').each(function () {


        cidade += $(this).attr('data-val');

    });
    alert(cidade);
    cidades.push(cidade);
});

要获取所有数据值,只需删除以下代码部分

if (current.children().size() > 0) { return true; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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