如何使用JavaScript获取被点击的数组元素的索引?

时间:2017-02-18 21:03:33

标签: javascript reactjs react-jsx

我有一个动态创建的span元素的数组列表。我想得到点击的span元素的索引。

boundItemClick(e) {
    console.log(e.target) //results <span>some label</span>
}
render() {
    var data=[];
    data.push (<div>
        <span>{textLabel} onClick={this.boundItemClick.bind(this)}</span>
        </div>
}

但是我无法以这种方式获取索引,获取单击数组元素索引的最佳方法是什么?

enter image description here

enter image description here

3 个答案:

答案 0 :(得分:2)

您可以将数据数组的当前长度作为索引传递给函数:

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.homepage),
url(r'^base/', views.basefile)
]

if settings.DEBUG:

urlpatterns += static(settings.STATIC_URL, document_root= settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, docuemt_root= settings.MEDIA_ROOT)

答案 1 :(得分:0)

Pure JS 解决方案。

注意:它从1开始计算,但如果您愿意,可以将其调整为从0开始计算索引。

var spans = document.getElementsByTagName('span');
[...spans].forEach((v,i) => v.addEventListener('click', function() {
  console.log(i+1);
}));
<span>one</span>
<span>two</span>
<span>three</span>

jQuery 解决方案。

$('span').click(function(){
  console.log($(this).index());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span>one</span>
<span>two</span>
<span>three</span>

答案 2 :(得分:0)

迭代为每个元素分配click事件监听器的元素,并使用lambda缓存并将索引传递给自定义处理函数。

&#13;
&#13;
// Initialize our dynamically created elements array
const elements = [];

// Simulate the creation of elements dynamically
const mkButton = text => Object.assign(document.createElement('button'),  { textContent: text })
for(var i = 10; i-- > 0;) elements.push(document.body.appendChild(mkButton('click')));

// Custom handler function
const handler = index => console.log(index);

// Assign the listener with the cached index to each element
elements.forEach((e, i) => e.addEventListener('click', event => handler(i), false));
&#13;
&#13;
&#13;