-4

How can we attach a Jquery function to a div that has been appended after the page was loaded, without any event being triggered.

In the example below defaultTab-28 is the div that has been appended later to the page.

<a href="javascript:toggleDiv('defaultTab-28')" 

and now I want to use toggle function on the "defaultTab-28" div like

function toggleDiv(divId){
     $("#" + divId).toggle();
}

If I use .delegate() or .on() I will have to specify the event like click etc, but in this case event trigger is not necessary.

Edit: to be a more precise:

I know using inline JS is not good when using JQuery, I could have used button click function from JQuery, but my question is : Is there any function like .on or .delegate to assign a function without an event

  1. I have added a div to an existing page
  2. When anybody clicks the tag I want the div that is passed to the javascript function which here is my div to use jquery toggle , but because this div is added later it cannot bind to toggle function
4

2 回答 2

1

Your code already works as is, you don't need to do anything about the div not existing yet.

http://jsfiddle.net/97GZb/

function toggleDiv(id){
    $("#" + id).toggle();
}

setTimeout(function(){
    $("body").append("<div id='defaultTab-28'>I'm the div!!!</div>");
},5000);

with this html:

<a href="javascript:toggleDiv('defaultTab-28')">Click me to toggle the div that will be appended in 5 seconds.</a> ​

And to answer your comment:

I know using inline JS is not good when using JQuery, I could have used button click function from JQuery, but my question is : Is there any function like .on or .delegate to assign a function without an event

No, there has to be an event of some kind to tell the javascript engine when to run the code. An element being added to the page is an Event, it is called a Mutation Event. there are also Mutation Observers that can handle this as well that were meant to be a replacement for Mutation Events. Neither of the two have very good cross-browser support.

于 2012-12-20T21:12:44.740 回答
0

JavaScript

function toggleDiv(divObj){
     $(divObj).toggle();
}

HTML (the thing you will append later):

<div onClick='toggleDiv(this);'></div>
于 2012-12-20T21:02:17.497 回答