我正在从JSON数据中创建一组元素:示例:
{
'name':'form',
'elements':[
{'name':'bt1','type':'button','value':'hello','order':'1'},
{'name':'img1','type':'image','value':'http://www.images.com/img.jpg','order':'2'}]
}
我用这个json创建一个表单,其中包含“元素”中描述的元素,代码如下:
(我在mumbo jquery代码中找到了这个草稿)
$('#container').html();//clears the container
for each element in elements do
switch element.type
case 'button':
$('#container').append('<input type="submit" value="'+element.value + ... etc');
end case
case 'image':
insert image bla bla bla
end switch
end for each
我想要检测一个元素是否被点击或另一种动作,比如鼠标悬停等等。我如何将它绑定到元素上?此外,如何在不破坏元素的情况下更新元素?
编辑:我暗示了一些重要的东西,我的错:我需要将元素javascript对象中的数据与生成的html元素链接起来。当操作被触发时,我检索的数据字段。这就是这一切的豪宅。
发布于 2012-05-02 19:26:07
构建表单非常容易,因为基本上已经映射了对象sytanx中元素的所有属性。因此,我们只需选择一个标记就可以创建这些元素,并将属性对象作为jQuery函数的第二个参数传入:
/* Container reference, counting variable */
var container = $("#container"), i = 0;
/* Clear out the container */
container.html("");
/* Cycle through each element */
while ( current = data.elements[i++] ) {
/* Evaluate the value of the current type */
switch ( current.type ) {
/* Since <input type='button|image'> are so similar, we fall-through */
case "button":
case "image" :
/* Choose a base element, pass in object of properties, and append */
$("<input>", current).appendTo(container);
break;
}
}
当涉及到注册单击或任何其他类型的事件时,我们将使用$.on
方法。因为我们传递的是一个选择器(在本例中是“输入”),这不仅将匹配所有当前元素,而且还将匹配所有未来的元素。
/* Listen for all clicks on input elements within the container */
container.on("click", "input", function(){
/* We have a button, and an image. Alert either the value or src */
alert( this.value || this.src );
});
发布于 2012-05-02 18:51:09
你有两个选择。您可以在创建元素之后绑定侦听器,如下所示:
var $input = $('<input type="submit" value="'+element.value + ... etc')
.focus(...).blur(...).etc.;
$('#container').append($input);
或者,您可以使用事件委托。在初始页面加载时,您可以这样做:
$("#container").on( "focus", "input", function(){...});
这将涵盖当前或稍后动态添加的#container
中的所有输入元素。您可以在医学博士中阅读更多关于事件委托的内容。
发布于 2012-05-02 18:51:43
要检测动态添加的元素上的事件,应将on()
用于jQuery 1.7+,而将.live()
用于以前的版本。
编辑:和yes,正如詹姆斯在评论中指出的,delegate()
总是被推荐而不是live()
。
https://stackoverflow.com/questions/10424444
复制相似问题