最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to work with dynamically created fields? - Stack Overflow

programmeradmin3浏览0评论

I have web layout, which can contains several links on it. Those links are dynamically created, using AJAX functions. And it works ok.

But, I don't know how can I work with those "dynamically created links" (ie. how to call some JS or jQuery function if I click on them). I guess that browser can not recognize them, since there are created after page is loaded.

Is there some function, that can "re-render" my page and elements on it?

Tnx in adv on your help!

I have web layout, which can contains several links on it. Those links are dynamically created, using AJAX functions. And it works ok.

But, I don't know how can I work with those "dynamically created links" (ie. how to call some JS or jQuery function if I click on them). I guess that browser can not recognize them, since there are created after page is loaded.

Is there some function, that can "re-render" my page and elements on it?

Tnx in adv on your help!

Share Improve this question asked Jul 18, 2010 at 18:06 user198003user198003 11.2k30 gold badges98 silver badges153 bronze badges 1
  • 2 Read up on the jQuery "live" and "delegate" facilities. – Pointy Commented Jul 18, 2010 at 18:08
Add a ment  | 

7 Answers 7

Reset to default 6

You can use the 2 following methods jQuery provides:

The first one, is the .live() method, and the other is the .delegate() method.

The usage of the first one is very simple:

$(document).ready(function() {
    $("#dynamicElement").live("click", function() {
        //do something
    });
}

As you can see, the first argument is the event you want to bind, and the second is a function which handles the event. The way this works is not exactly like a "re-rendering". The mon way to do this ( $("#dynamicElement").click(...) or $("#dynamicElement").bind("click", ...) ) works by attaching the event handler of a determinate event to the DOM Element when the DOM has properly loaded ($(document).ready(...) ). Now, obviously, this won't work with dynamically generated elements, because they're not present when the DOM first loads.

The way .live() works is, instead of attaching the vent handler to the DOM Element itself, it attaches it with the document element, taking advantage of the bubbling-up property of JS & DOM (When you click the dynamically generated element and no event handler is attached, it keeps looking to the top until it finds one).

Sounds pretty neat, right? But there's a little technical issue with this method, as I said, it attaches the event handler to the top of the DOM, so when you click the element, your browser has to transverse all over the DOM tree, until it finds the proper event handler. Process which is very inefficient, by the way. And here's where appears the .delegate() method.

Let's assume the following HTML estructure:

<html>
<head>
...
</head>
<body>
    <div id="links-container">
        <!-- Here's where the dynamically generated content will be -->
    </div>
</body>
</html>

So, with the .delegate() method, instead of binding the event handler to the top of the DOM, you just could attach it to a parent DOM Element. A DOM Element you're sure it's going to be somewhere up of the dynamically generated content in the DOM Tree. The closer to them, the better this will work. So, this should do the magic:

$(document).ready(function() {
    $("#links-container").delegate("#dynamicElement", "click", function() {
        //do something
    });
}

This was kind of a long answer, but I like to explain the theory behind it haha.

EDIT: You should correct your markup, it's invalid because: 1) The anchors does not allow the use of a value attribute, and 2) You can't have 2 or more tags with the same ID. Try this:

<a class="removeLineItem" id="delete-1">Delete</a> 
<a class="removeLineItem" id="delete-2">Delete</a> 
<a class="removeLineItem" id="delete-3">Delete</a>

And to determine which one of the anchors was clicked

$(document).ready(function() {
    $("#links-container").delegate(".removeLineItem", "click", function() {
        var anchorClicked = $(this).attr("id"),
            valueClicked = anchorClicked.split("-")[1];    
    });
}

With that code, you will have stored in the anchorClicked variable the id of the link clicked, and in the valueClicked the number associated to the anchor.

In your page initialization code, you can set up handlers like this:

$(function() {
  $('#myForm input.needsHandler').live('click', function(ev) {
    // .. handle the click event
  });
});

You just need to be able to identify the input elements by class or something.

How are these links dynamically created? You can use use the correct selector, given that they are using the same class name or resides in the same tag, etc.

consider the html form

<form>
  <input type="text" id="id" name="id"/>
  <input type="button" id="check" name="check value="check"/>
</form>

jquery script

$('#check).click(function()  {
   if($('#id).val() == '') {
      alert('load the data!!!!);
   }
});

here on clicking the button the script check the value of the textbox id to be null. if its null it will return an alert message.... i thin this is the solution you are looking for.....

have a nice day..

Noramlly , the browser process response HTML and add it to DOM tree , but sometimes , current defined events just not work , simply reinitialize the event when u call the ajax request ..

All you need to do to work with dynamically created elements is create identifiers you can locate them with. Try the following code in console of Firebug or the developer tools for Chrome or IE.

$(".everyonelovesstackoverflow").html('<a id="l1" href="http://www.google.">google</a> <a id="l2" href="http://www.yahoo.">yahoo</a>');
$("#l1").click(function(){alert("google");});
$("#l2").click(function(){alert("yahoo");});

You should now have two links where the ad normally is that were dynamically created, and than had an onclick handler added to bring up an alert (I didn't block default behaviour, so it will cause you to leave the page.)

jQuery's .live will allow you to automatically add handlers to newly created element.

If your links are ing in via AJAX, you can set the onclick attributes on the server. Just output the links into the AJAX like this:

<a href="#" onclick="callYourFunctionHere();return false;">Holy crap I'm a link</a>

The return false makes sure the link doesn't reload the page.

Hope this helps!

发布评论

评论列表(0)

  1. 暂无评论