简体   繁体   中英

How to call a function when clicking a dynamically generated link, using jQuery?

I am creating more than 1 <a href="#"></a> elements dynamically. The id attribute is also dynamically assigned. Like <a href="#" id='delete"+id+"'></a> . ID will becomes like delete01, delete02, ... I want to call a function when clicking any one of these element. I just know,

$("#someId").click(this.someFunction()); 

calls the function, when the element with the ID someId clicked.

The generated HTML looks like,

<a id="delete26" href="#" class="delete">Delete</a>
<a id="delete27" href="#" class="delete">Delete</a>
<a id="delete28" href="#" class="delete">Delete</a>

The JavaScript code that generates the above html looks like,

html += "<a class='delete' href='#' id='delete"+post.id+"'>Delete</a>";

Here, my ID's were dynamically generated. So, how shall i call a function when any one of the element got clicked.

Any suggestions!!!

Thanks!

The nicest way to do this is with .delegate() . This function uses a feature of Javascript called "event bubbling", which means that every time an event is fired on an element (such as click, focus, blur, mouseover) it is also fired on all that element's parent elements. You can therefore use a common ancestor element to trap all the events. The advantage of this is that you can add handlers for events that don't yet exist.

jQuery automates a lot of this for you:

$('#container').delegate('a.delete', 'click', this.someFunction);

This is very similar to live() , but in my opinion has nicer syntax and a slight performance increase.

Note that this example assumes that your links are all contained in an element with the id container .

You can use jQuery .live()

$(".delete").live("click", function() {
  // take some action
  return false;
});

And, if you want to call a named function you'd use the following. Note that I'm not using ()

$(".delete").live("click", this.someFunction)

You could use the following selector:

$('a[id^=delete]').click(function() {
    var number = this.id.match(/^delete(\d+)$/)[1];
    return false;
});

使用live方法,并可能使用一个选择器作为$('a.delete')我假设内容是通过ajax加载的,如果没有,则可以用$('a.delete')罚款

I have used this quite a lot. I don't know if it's the best solution, but try it anyways:

In your JavaScript have a function similar to this:

function doStuff(id)
{
    alert("doing things from ID: "+id);
}

Then with your href s do this (using '26' as example ID):

<a href="#" onclick="doStuff(26)" id="26">

It's probably crap but it works

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