【问题标题】:Can I have only one Index from a click event selected Item?我可以从单击事件中选择的项目中只有一个索引吗?
【发布时间】:2015-02-24 23:30:02
【问题描述】:

我在编辑和删除所选条目时遇到问题。我认为这是因为我只得到一个索引。

我如何选择事物:

$("#liste").click(function selectList (event) {
        var target = $( event.target );
        if ( target.is( "li" ) ) {
            target.toggleClass('selected');
        }
    });

问题就在这里:

$('.selected').attr("index");

我只从所选项目中获取第一个索引,但我希望获得每个所选项目的所有索引。如有问题请查看I have a Special Idea about an Edit function 或随时提问!

【问题讨论】:

    标签: jquery events onclick target targeting


    【解决方案1】:

    attr() 如您所说,将从匹配集中的第一个元素返回属性。如果您想要所选对象的所有index 属性,请使用map()

    var indices = $('.selected').map( 
      function() {
        return $(this).attr('index');
      }
    );
    

    var indices = $('.selected').map(function() {
      return $(this).attr('index');
    });
    
    console.log(indices);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div class="selected" index="one"></div>
    <div class="selected" index="two"></div>
    <div index="three"></div>
    <div class="selected" index="four"></div>
    <div index="five"></div>

    【讨论】:

    • 那么map创建了一个包含所有索引的Object?
    • 不,map() 返回某个函数的结果,对数组中的每个元素执行;结果是也是一个数组。请参阅the docs 了解更多信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    相关资源
    最近更新 更多