[英]How can I pass an object reference to a function in Javascript / jQuery?
I have two functions in a data tool that I'm making - showEditDv(object)
and editDv(object)
. 我在数据工具中有两个函数 -
showEditDv(object)
和editDv(object)
。 If you haven't already guessed, Dv
stands for Data Value. 如果您还没有猜到,
Dv
代表数据价值。 showEditDv
is called when you click on the edit data icon. 单击编辑数据图标时会调用
showEditDv
。 It generates an Opentip tooltip that (will) allow you to edit data, and is called like this: showEditDv(this);
它会生成一个Opentip工具提示,它将允许您编辑数据,并且可以像这样调用:
showEditDv(this);
in an onclick attribute. 在onclick属性中。 Here is the code for that function (no, there aren't inline comments in the actual thing):
这是该函数的代码(不,实际上没有内联注释):
function showEditDv(object) {
var name = $(object).attr("data-name"); // string(name) now holds the name of the data value
var input = new Opentip($(object), {target: null, showOn: null, hideTrigger: "closeButton"});
input.setContent("<label>Name:</label><input type='text' value='" + name + "' class='dv-add-name' /><label>Value:</label>input type='text' class='dv-add-value' value='" + data[name] + "' /><button onclick='editDv(" + $(object) /*<-- problem */ + ");'>Apply</button>");
input.show();
}
The problem arises when the editDv()
function is called by the 'Apply' button. 当“应用”按钮调用
editDv()
函数时,会出现问题。 Because the object is being referred to in a string (I think!), the object reference is printed as [object Object]
, and the function cannot hide the Opentip because it doesn't have a reference for it. 因为对象是在字符串中引用的(我认为!),对象引用被打印为
[object Object]
,并且该函数无法隐藏Opentip,因为它没有对它的引用。 Here is the code for editDv()
: 这是
editDv()
的代码:
function editDv(object) {
var input = $(object).data("opentips")[0]; // data("opentips") is an array of objects
input.hide();
}
So my question is: how can I pass the input
object from showEditDv
to editDv
as an argument, or is there a better way to do this entirely? 所以我的问题是:如何将
input
对象从showEditDv
给editDv
作为参数,还是有更好的方法完全执行此操作?
Don't call the function inline with an onclick event, use jQuerys .on() function instead: 不要使用onclick事件内联调用函数,而是使用jQuerys .on()函数:
Like so: 像这样:
function showEditDv(object) {
var name = $(object).data("name"); // use .data()
var input = new Opentip($(object), {target: null, showOn: null, hideTrigger: "closeButton"});
input.setContent("<label>Name:</label><input type='text' value='" + name + "' class='dv-add-name' /><label>Value:</label>input type='text' class='dv-add-value' value='" + data[name] + "' /><button class='callEditDv'>Apply</button>");
input.show();
}
AND 和
$('.callEditDv').on('click', function() {
// access the button like this: $(this)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.