Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

javascript - Getting access to a jquery element that was just appended to the DOM

I am simply appending an element that is on the DOM like:

$("#div_element").append('<a href="#">test</a>');

Right after I append it I need access to the element I just made in order to bind an click function to it, I tried:

$("#div_element").append('<a href="#">test</a>').click(function(){alert("test")});

But the above didn't work. I could uniquely id the element but that seems like a bit to much work when perhaps there is a way I can get the element right after I append it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do this:

var el = $('<a href="#">test</a>');

$("#div_element").append(el);

el.click(function(){alert("test")});

// or preferrably:
el.on('click', function(){alert("test")});

The append function accepts two types of arguments: a string or a jQuery element. In case a string is passed in, it will create a jQuery element internally and append it to the parent element.

In this case, you want access to the jQuery element yourself, so you can attach the event handler. So instead of passing in the string and let jQuery create an element, you have to create the element first and then pass it to the append-function.

After you've done that, you still have access to the jQuery element to be able to attach the handler.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...