2014-10-04 22 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