简体   繁体   中英

How to detect clicks on generated elements?

I'm making a group of elements from a JSON data: Example:

{
'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:

(I've got this draft in mumbo jumbo + jquery code)

$('#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. 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. You can read more about event delegation in the on docs .

To detect events on dynamically added elements, you should use on() for jQuery 1.7+ and .live() for previous versions.

EDIT: And yes, as James pointed out in the comments, delegate() is always recommended over live() .

Building the form is really very easy, since you've basically mapped all of the attributes of the elements in an object 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:

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

if your js code is short, just add your js code in the append function. 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. and add event to the 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 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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