我正在使用 jQuery 可排序列表,您可以在其中从可拖动列表中删除(克隆)项目。我希望用户能够更改放置的元素上的一些文本。因此,我显示该值,并在隐藏的输入字段中保留一个副本。
单击任何元素时,都会打开一个 jquery 对话框,并且文本将设置在对话框的文本输入中。关闭时,新值将在元素文本和隐藏输入上再次设置。
对话框如何知道哪个元素请求文本更改?
现在我正在使用全局变量来保存该信息。但我觉得它很丑。一定有某种方法可以让发送者打开dialog.open?
// Global for holding the dialog sender
var dialogSender = null;
// Edit element
$('.element').live('click', function() {
dialogSender = $(this);
// prev() is the hidden input
$('#dialog-form input[name=content]').val($(this).prev().val());
$('#dialog-form').dialog('open');
});
// Dialog for editing elements
$('#dialog-form').dialog({
autoOpen: false,
modal: true,
buttons: {
'Ok': function() {
val = $('#dialog-form input[name=content]').val();
// Set the text back to the element and the hidden input
dialogSender.text(val).prev().val(val);
$(this).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
}
});
最佳答案
您可以使用data()将单击的按钮与对话框小部件关联起来,然后在 Ok
按钮处理程序中读回该信息:
$(".element").live("click", function() {
var $this = $(this);
// prev() is the hidden input
$("#dialog-form input[name=content]").val($this.prev().val());
$("#dialog-form").data("dialogSender", $this).dialog('open');
});
'Ok': function() {
var $this = $(this),
val = $("#dialog-form input[name=content]").val();
// Set the text back to the element and the hidden input.
$this.data("dialogSender").text(val).prev().val(val);
$this.dialog("close");
},
关于jquery - 如何从 jQuery 对话框访问发送者对象或按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9698213/