简体   繁体   English

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

[英]How to detect clicks on generated elements?

I'm making a group of elements from a JSON data: Example: 我正在从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'}]
}

What i do with this json is create a form with the elements described in 'elements' with a code like this: 我用这个json做的是创建一个带有'elements'中描述的元素的表单,代码如下:

(I've got this draft in mumbo jumbo + jquery code) (我用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

I want to detect if an element gets clicked or another kind of action, like mouse hover, etc. How do i bind this to the elements? 我想检测一个元素是否被点击或其他类型的操作,如鼠标悬停等。如何将其绑定到元素? Also, how do i update the elements without destroying them? 另外,如何在不破坏元素的情况下更新元素?

EDIT : I implied something important, my bad: I need to link the data in the elements javascript object with the generated html elements. 编辑 :我暗示一些重要的东西,我的坏:我需要将元素javascript对象中的数据与生成的html元素链接起来。 A data field wich i retrieve when an action is triggered. 触发操作时检索的数据字段。 That's the porpouse of all this. 这就是所有这一切的特征。

You have two options. 你有两个选择。 You can bind the listeners after you've created the elements, like this: 您可以在创建元素后绑定侦听器,如下所示:

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

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

Or, you can use event delegation. 或者,您可以使用事件委派。 On your initial page load you can do this: 在初始页面加载时,您可以执行以下操作:

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

This will cover all input elements in #container either currently or dynamically added later. 这将涵盖#container中当前或稍后动态添加的所有输入元素。 You can read more about event delegation in the on docs . 您可以在on docs上阅读有关事件委派的更多信息。

To detect events on dynamically added elements, you should use on() for jQuery 1.7+ and .live() for previous versions. 要检测动态添加元素上的事件,您应该使用on()表示jQuery 1.7+和.live()用于以前的版本。

EDIT: And yes, as James pointed out in the comments, delegate() is always recommended over live() . 编辑:是的,正如詹姆斯在评论中指出的那样, delegate()始终被推荐为live()

Building the form is really very easy, since you've basically mapped all of the attributes of the elements in an object sytanx. 构建表单非常简单,因为您基本上映射了对象sytanx中元素的所有属性。 As such, we can create these elements with nothing more than choosing a tag, and passing the attribute object in as the second parameter of the jQuery function: 因此,我们可以创建这些元素,只需选择一个标记,并将属性对象作为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;
  }
}

When it comes to registering clicks, or any other type of event, we'll use the $.on method. 在注册点击或任何其他类型的事件时,我们将使用$.on方法。 Because we're passing in a selector ( "input" in this case ), this will not only match all present elements, but all future elements as well. 因为我们传入一个选择器(在这种情况下是“输入”),所以这不仅会匹配所有现有元素,还会匹配所有未来元素。

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

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

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

if your js code is long, you can add an id to your new element. 如果你的js代码很长,你可以为你的新元素添加一个id。 and add event to the id. 并向id添加事件。

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

Either bind the element directly 要么直接绑定元素

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

or put the bind on a parent that checks the select of what was click inside.. 或者将绑定放在父级上,以检查内部点击的选择。

$('#container').on('click', 'input', function() { 
    // do something 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM