1

我正在从 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 jumbo + 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 元素链接起来。触发操作时我检索的数据字段。这就是这一切的目的。

4

5 回答 5

2

你有两个选择。您可以在创建元素后绑定侦听器,如下所示:

var $input = $('<input type="submit" value="'+element.value + ... etc')
                  .focus(...).blur(...).etc.;

$('#container').append($input);

或者,您可以使用事件委托。在初始页面加载时,您可以这样做:

$("#container").on( "focus", "input", function(){...});

这将涵盖#container当前或以后动态添加的所有输入元素。您可以在on docs中阅读有关事件委托的更多信息。

于 2012-05-03T02:51:09.980 回答
1

要检测动态添加的元素上的事件,您应该使用on()jQuery 1.7+ 和.live()以前的版本。

编辑:是的,正如詹姆斯在评论中指出的那样,delegate()总是推荐超过live().

于 2012-05-03T02:51:43.427 回答
1

构建表单非常简单,因为您基本上已经映射了对象 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方法。因为我们传入了一个选择器(在本例中为“input”),这不仅会匹配所有当前元素,还会匹配所有未来元素。

/* 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 );
});

在线演示:http: //jsbin.com/izimut/edit#javascript,html

于 2012-05-03T03:26:07.547 回答
0

如果您的 js 代码很短,只需在 append 函数中添加您的 js 代码即可。 append('<input type="submit" onclick="xxxx" value="'+element.value + ... etc');

如果你的 js 代码很长,你可以给你的新元素添加一个 id。并将事件添加到 id。

$("#idxx").click(function(){alert("Hello");});
于 2012-05-03T02:51:21.490 回答
0

直接绑定元素

$input = $('<input type="submit" value="'+element.value + ... etc');
$input.on('click', function() { 
    // do something 
}
$('#container').append($input);

或将绑定放在检查内部单击内容的选择的父级上。

$('#container').on('click', 'input', function() { 
    // do something 
}
于 2012-05-03T02:52:30.853 回答