[英]Saving custom data to dom elements using jquery only once
I am creating dynamic controls using jQuery by reading the query string parameter. 我正在通过读取查询字符串参数使用jQuery创建动态控件。 These controls can be dragged to lay them in neat manner, after the drop event in drag/drop I would update the position and state of control through hidden field. 可以拖动这些控件以使其整齐地放置它们,在拖放事件发生后,我将通过隐藏字段更新控件的位置和状态。 It's just that my implementation now updates data at each drop which is not nice. 只是我的实现现在每次删除时都会更新数据,这并不好。 I also did this through event but did not work well 我也通过活动来做到这一点,但效果不佳
/*Create controls when only query string exists*/
if (config.params) {
//parse the query string json as a object
//ex:{type:"textbox",x:100,y:200,label:Name}
var params = $.parseJSON(config.params);
//for each control in json add it to document body
$(params).each(function (idx, obj) {
var id = new Date();//for generating dynamic id
id = id.getTime();
$("<span>").addClass(obj.css).load(function (ev) {
var a = this;
$(a).data("keys", {
key: $("label", a).text()**certainly label wont be found**,
value: $("input[name]:hidden", a)
});
}).
easydrag().ondrop(function (e, el) {
//easydrag drag drop plugin
var a = $(el),
b = a.data("keys"),
key = b.key,
value = b.value;
value.val(key + "$" + e.pageX + "$" + e.pageY);
}).
css({
position: "absolute",
top: obj.y,
left: obj.x
}).
append($("<label>", {
"for": id
}).
html(obj.label).
append(config.ELEMENTS(obj.type).attr("id", id))).
append($("<input>", {
"type": "hidden",
"name": "CONTROL$POSITION",
"id": "control_position_" + idx
})).
appendTo("form");
});
}
label
and hidden fields
. 但是由于这是加载事件,所以我将没有内部label
和hidden fields
。 I need to set the data on element span
only once, since during drop event
i will access the label and hidden field to update the current position of the control. 我只需要设置一次元素span
上的数据,因为在drop event
期间,我将访问标签和隐藏字段以更新控件的当前位置。 I don't want to query the dom
on each drop for the label
and hidden field
that's my purpose. 我不想 query the dom
上的每一滴的label
和hidden field
这就是我的目的。 Get rid of load
, and temporary store a reference to the element. 摆脱load
,并临时存储对该元素的引用。 Execute the code after the element has fully finished creating: 在元素完全完成创建之后执行代码:
var span = $("<span>");
span.addClass(obj.css).
easydrag(). //et cetera
....
appendTo("form");
//After the element has finished:
$(span).data("keys", {
key: $("label", span).text(),
value: $("input[name]:hidden", span)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.