如何检测生成元素的点击?

时间:2012-05-03 02:46:52

标签: javascript jquery json

我正在从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做的是创建一个带有'elements'中描述的元素的表单,代码如下:

(我用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元素链接起来。触发操作时检索的数据字段。这就是所有这一切的原因。

5 个答案:

答案 0 :(得分:2)

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

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

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

或者,您可以使用事件委派。在初始页面加载时,您可以执行以下操作:

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

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

答案 1 :(得分:1)

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

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

答案 2 :(得分: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方法。因为我们传入选择器(在这种情况下是“输入”),所以这不仅会匹配所有现有元素,还会匹配所有未来元素。

/* 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

答案 3 :(得分:0)

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

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

$("#idxx").click(function(){alert("Hello");});

答案 4 :(得分: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 
}