2012-01-21 47 views
2

我正在使用js/jquery創建可拖動圖。圖形有兩個可拖動的元素,可以在後面的圖形上選擇值。我現在的問題是,下一步將能夠乘一個頁面上最多六個圖形,我做了,現在當圖形動態創建時,只有引用元素的方法是$(this),如何將兩個元素相同的功能?在多個Html元素上使用一個Javascript/Jquery函數?

編輯:

function drag_function(event, ui) { 

    var $selFirst = $(".second :nth-child(1)"), 
     $selSecond = $(".second :nth-child(2)"), 
     cachedWidth = $selFirst.outerWidth(); 

    var $firstRightBorder = $selFirst.position().left + 1, 
     $secondLeft = $selSecond.position().left, 
     diff = $firstRightBorder - $secondLeft; 
} 

如果我使用:

function drag_function(event, ui) { 

    var $selFirst = $(this), 
     $selSecond = $(this), 
     cachedWidth = $selFirst.outerWidth(); 

    var $firstRightBorder = $selFirst.position().left + 1, 
     $secondLeft = $selSecond.position().left, 
     diff = $firstRightBorder - $secondLeft; 
} 

也不起作用?

答:

var $selFirst = $(this).parent().children().eq(0), 
     $selSecond = $(this).parent().children().eq(1) 

回答

1

它仍然是不清楚你想要達到的目標。我猜是這樣。請在下面給出的示例中拖放div。

http://jsfiddle.net/diode/8wxCb/1/

在事件處理函數和thisevent.currentTarget指用於已發生事件的對象。

爲如:

button1.onclick = function(event){ 

    console.log(this); // button1 
    console.log(event.currentTarget); // button1 

} 

所以,如果你的監聽器添加相同的功能很多,在功能,您可以檢查

if(this == button1){ 

}else if(this == button2){ 

} 

if(this.id == "button1"){ 

}else if(this.id == "button2"){ 

} 

當你的對象裏面的函數可以直接讀寫它的屬性

見:http://jsfiddle.net/diode/nZQy6/

+0

只是添加,在此組件的所有元素創建動態的,可以刪除的,所以我不能去一說,如果「Button1的」 ......因爲用戶可以添加/刪除,ID名稱動態構建? –

相關問題