问题
I have styled a list to look like a select box and I want to fire a function when the user clicks an element in the list however the element is loaded via AJAX
and hence isn't there when the page loads and I can't bind an onclick
event to it onDomReady
.
If I had it as a normal select list I could just tag on an onChange
event to the <select>
field, but I obviously can't do that in my case.
My HTML:
<div id="main_category_field" class="fields">
<div class="cat_list">
<ul>
<li class=""><a rel="1866" href="#1866">Sports Cards ></a></li>
<li class=""><a rel="1867" href="#1867">Gaming Cards ></a></li>
<li class=""><a rel="1868" href="#1868">Non-Sport Cards ></a></li>
<li class=""><a rel="1869" href="#1869">Supplies & Storage ></a></li>
<li class=""><a rel="1940" href="#1940">Video Games </a></li>
</ul>
</div>
<div class="contentClear"></div>
</div>
How can I run a function whenever the user clicks any of these options? Also would be great if you could also advise how to pass the respective value of the rel
back when they click an option.
Using jQuery so options in that would be preferred.
Edit: Meant to say that the main element main_category_field
is a static element. The elements inside are loaded via AJAX.
回答1:
you need to delegate your elements to static parent , if the element is added dynamically using on()
try this
$(document).on('click','li a',function(e){
e.preventDefault();
var rel = this.rel;
//or using attr()
var rel=$(this).attr('rel');
alert(rel);
});
however delegating it to its closest static parent(present at a time of insertion) is better than document itself.. so if you are adding the list inside main_category_field
div.. then you can use
$('#main_category_field').on('click','li a',function(e){
//same stuff
回答2:
The key word is event delegation
. If you want to assign event handlers to dynamically added elements for which you know their "future" selectors, you should use the .on()
method on an (already existing) parent element of those dynamic elements.
The second parameter to .on()
is then the selector of the dynamically added elements
$(document).on('click', '.cat_list li a', function(e) {
alert(this.rel); // show the "rel" attribute of the clicked a element
e.preventDefault(); // to prevent the default action of anchor elements
});
回答3:
Use .on
for listen dynamically created dom elements as follows
$(document).on('click','div.cat_list ul li a',function(){
var rel=$(this).attr('rel');//to get value of rel attribute
alert(rel);
//other operations
});
回答4:
To bind an event handler to an element that does not yet exist on the page use on
.
$(document).on("click", "#main_category_field", function(e){
e.preventDefault();
var rel = e.target.rel;
});
JS Fiddle: http://jsfiddle.net/82bAb/
来源:https://stackoverflow.com/questions/21111957/applying-an-onclick-event-to-an-element-that-doesnt-exist-on-page-load