2014-10-04 20 views
0
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和代码进一步上使用它,因此而不是命名id's使用JavaScript

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

我想让他们与js。

+0

阿伯杜听所有的点击JS – loveNoHate 2014-10-04 10:54:22

+0

我的意思让他们,我想找到id's他们点击 – user2615859 2014-10-04 11:00:58

+0

@ user2615859后 - 使用**'$(本).attr('id');'**获取当前元素的ID。 – prog1011 2014-10-04 11:20:35

回答

0

怎么是这样的:

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

添加boxElementClass您的所有元素,并点击元素的ID将被存储在clickedElementId。

+0

不应该是:'var clickedElementId = event.target.id;'? – 2014-10-04 11:24:25

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); 
    } 
}); 
+0

你可以添加一个如何重写代码的例子。谢谢 – user2615859 2014-10-04 11:12:53

+0

我已更新示例。像这样的东西,如果我正确地得到你的问题 – 2014-10-04 11:21:14