使用javascript获取被点击元素的id

时间:2014-10-04 10:51:46

标签: javascript jquery

window.onload = function () {

boxElement = document.getElementById('button1_id'),
boxMove = document.getElementById('button2_id');

if (boxElement) {
boxElement.addEventListener('click', function () {

    var boxLeftPos = boxMove.offsetLeft,
        rightper = boxMove.offsetRight;

    if (boxLeftPos > 0) {
        direction = (boxMove.offsetWidth - 50)*-1;
        boxMove.style.left = (direction) + 'px';
    }

    if (boxLeftPos < 1) {
        direction = 10;
        boxMove.style.right = (rightper) + '%';
        boxMove.style.left = '';
    }

});
}
};

我想获取点击按钮的按钮ID并在代码中进一步使用它,因此不是命名id的

boxElement = document.getElementById('button1_id'),
boxMove = document.getElementById('button2_id');

我想用js来获取它们。

2 个答案:

答案 0 :(得分:0)

这样的事情怎么样:

$('.boxElementClass').click(function(event){
    var clickedElementId = $(event.target.id);
});

将boxElementClass添加到您的所有元素,并且单击元素的id将存储在clickedElementId中。

答案 1 :(得分:0)

您可以通过document

收听所有点击
function makeYourMove(boxMove) {

    var boxLeftPos = boxMove.offsetLeft,
        rightper = boxMove.offsetRight;

    if (boxLeftPos > 0) {
        direction = (boxMove.offsetWidth - 50)*-1;
        boxMove.style.left = (direction) + 'px';
    }

    if (boxLeftPos < 1) {
        direction = 10;
        boxMove.style.right = (rightper) + '%';
        boxMove.style.left = '';
    }

}

document.addEventListener('click', function(event) {
  var element;

  element = event.target;

  if (element.id === 'button1_id') {
    boxMove = document.getElementById('button2_id');

    makeYourMove(boxMove);
  }
});
相关问题