我正在使用 js/jquery 来创建可拖动的图形。 Graph 有两个可拖动元素,它们基于后面的图形选择值。我现在的问题是下一步将能够在一页上最多乘以六个图形,我做到了,现在当动态创建图形时,引用元素的唯一方法是通过 $(this)
,如何在同一个函数中处理两个元素?
编辑:
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)
最佳答案
目前还不清楚你想要达到什么目的。我猜是这个。请在下面给出的示例中拖放 div。
http://jsfiddle.net/diode/8wxCb/1/
在事件处理函数中,this
和 event.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"){
}
当您在函数中获取对象时,您可以直接读/写它的属性
关于javascript - 在多个 Html 元素上使用一个 Javascript/Jquery 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8953998/