获取点击类索引javascript

时间:2012-12-01 09:45:50

标签: javascript

我有3个div与类:wpEdit和onClick:alertName()

<div class="wpEdit" onClick="alertName()">Bruce Lee</div>
<div class="wpEdit" onClick="alertName()">Jackie Chan</div>
<div class="wpEdit" onClick="alertName()">Jet li</div>

点击后,我想知道点击的Div的类wpEdit的索引:

function alertName(){
    //Something like this
    var classIndex = this.className.index; // This obviously dosnt work
    alert(classIndex); 
}

当点击Bruce Lee时,它应警告:0 当点击成龙时,它应该警告:1 当点击Jet Li时,它应该警告:2

我需要知道在

上点击了哪个class =“wpEdit”

5 个答案:

答案 0 :(得分:5)

试试这个

function clickedClassHandler(name,callback) {

    // apply click handler to all elements with matching className
    var allElements = document.body.getElementsByTagName("*");

    for(var x = 0, len = allElements.length; x < len; x++) {
        if(allElements[x].className == name) {
            allElements[x].onclick = handleClick;
        }
    }

    function handleClick() {
        var elmParent = this.parentNode;
        var parentChilds = elmParent.childNodes;
        var index = 0;

        for(var x = 0; x < parentChilds.length; x++) {
            if(parentChilds[x] == this) {
                break;
            }

            if(parentChilds[x].className == name) {
                index++;
            }
        }

        callback.call(this,index);
    }
}

用法:

clickedClassHandler("wpEdit",function(index){
    // do something with the index
    alert(index);

    // 'this' refers to the element 
    // so you could do something with the element itself
    this.style.backgroundColor = 'orange';
});

答案 1 :(得分:2)

您可能希望在代码中解决的第一件事是内联HTML绑定。

您可以对每个元素使用document.addEventListener,也可以依赖event delegation

最常用的事件委派实现是jQuery。如果您已经在使用jQuery,那就可以了!

或者我也是我自己的小delegate utility

const delegate = (fn, selector) => {
  return function handler(event) {
    const matchingEl = matches(event.target, selector, this);
    if(matchingEl != null){
      fn.call(matchingEl, event);
    }
  };
};

const matches = (target, selector, boundElement) => {
  if (target === boundElement){
    return null;
  }
  if (target.matches(selector)){
    return target;
  }
  if (target.parentNode){
    return matches(target.parentNode, selector, boundElement);
  }
  return null;
};

这是注册事件监听器的方式。

document.getElementById('#parent')
  .addEventListener('click', delegate(handler, '.wpEdit'));

这就是你如何获得生成事件的元素的索引。

const handler = (event) => {
  console.log(Array.prototype.indexOf.call(event.currentTarget.children, event.target));
}

现场演示:

const delegate = (fn, selector) => {
  return function handler(event) {
    const matchingEl = matches(event.target, selector, this);
    if (matchingEl != null) {
      fn.call(matchingEl, event);
    }
  };
};

const matches = (target, selector, boundElement) => {
  if (target === boundElement) {
    return null;
  }
  if (target.matches(selector)) {
    return target;
  }
  if (target.parentNode) {
    return matches(target.parentNode, selector, boundElement);
  }
  return null;
};

const handler = (event) => {
  console.log(Array.prototype.indexOf.call(event.currentTarget.children, event.target));
}

document.getElementById('parent')
  .addEventListener('click', delegate(handler, '.wpEdit'));
<div id="parent">
  <div class="wpEdit">Bruce Lee</div>
  <div class="wpEdit">Jackie Chan</div>
  <div class="wpEdit">Jet li</div>
</div>

答案 2 :(得分:1)

如果你想根据你的班级wpEdit得到div的索引,你可以这样做:

HTML:

<div class="wpEdit">Bruce Lee</div>
<div class="wpEdit">Jackie Chan</div>
<div class="other">Other</div>
<div class="wpEdit">Jet li</div>

JS:

$(".wpEdit").bind("click", function(){
    var divs = $(".wpEdit");
    var curIdx = divs.index($(this));

    alert(curIdx);
});

实例:http://jsfiddle.net/pJwzc/

有关jQuery的索引函数的更多信息:http://api.jquery.com/index/

答案 3 :(得分:0)

使用香草javascript,这对我有效:

var wpEdits = document.querySelectorAll(".wpEdit");

for (let i = 0; i < wpEdits.length; i++)
  wpEdits[i].addEventListener("click", showID);

function showID(evt) {
  for (let i = 0; i < wpEdits.length; i++)
    if(wpEdits[i] == evt.target)    
      alert(i);
}

虽然可能不是最好的解决方案,因为我还是js新手。

由于我是JS的新手,因此请对以下内容进行一些说明:

(第1行) 这类似于var wpEdits = document.getElementsByClassName("wpEdit");。它将把html文件中的class="wpEdit"的所有实例分配给wpEdits变量。

(第3行和第4行) 这两行将导致在class="wpEdit"上的任何单击都会调用下面定义的函数showID()

(第6行和第10行) 当发生点击事件时,浏览器会将被点击项目的唯一属性传递给evt变量。然后在for循环中使用它来与所有可用实例进行增量比较。 evt.target用于到达实际目标。找到匹配项后,它将提醒用户。

为避免浪费CPU时间,建议运行break;以在找到匹配项后立即退出循环。

答案 4 :(得分:0)

我不明白,为什么人们在以前的答案中添加新功能,所以...

const wpEdit = document.getElementsByClassName('wpEdit');
for(let i = 0; i < wpEdit.length; i++){
  wpEdit[i].addEventListener('click',function(){
    alert(i);
  });
}

我刚刚使用循环添加了“ click”事件。而且[i]已经是当前点击的班级索引...

FIDDLE