使用 JavaScript 获取单击元素的 ID

getting the id of the clicked element using javascript

本文关键字:ID 元素 单击 JavaScript 获取 使用      更新时间:2023-09-26
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得到它们。

像这样的事情怎么样:

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

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

您可以通过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);
  }
});