将onclick事件应用于页面加载时不存在的元素 [英] Applying an onclick event to an element that doesn't exist on page load

查看:112
本文介绍了将onclick事件应用于页面加载时不存在的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将列表看起来像一个选择框,我想在用户单击列表中的元素时触发一个函数,但是元素是通过 AJAX加载因此在页面加载时不存在,我无法将 onclick 事件绑定到 onDomReady

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.

如果我将它作为普通选择列表,我可以在 onChange 事件上标记为< select> 字段,但我显然不能这样做。

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.

我的HTML:

<div id="main_category_field" class="fields">
    <div class="cat_list">
        <ul>
            <li class=""><a rel="1866" href="#1866">Sports Cards &gt;</a></li>
            <li class=""><a rel="1867" href="#1867">Gaming Cards &gt;</a></li>
            <li class=""><a rel="1868" href="#1868">Non-Sport Cards &gt;</a></li>
            <li class=""><a rel="1869" href="#1869">Supplies &amp; Storage &gt;</a></li>
            <li class=""><a rel="1940" href="#1940">Video Games </a></li>
        </ul>
    </div>
    <div class="contentClear"></div>
</div>

每当用户点击任何这些选项时,我该如何运行某个功能?如果您还可以建议如何在点击选项时传递 rel 的相应值,那也很棒。

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.

使用jQuery这样的选项将是首选。

Using jQuery so options in that would be preferred.

编辑:意味着主要元素 main_category_field 是一个静态元素。内部元素通过AJAX加载。

Meant to say that the main element main_category_field is a static element. The elements inside are loaded via AJAX.

推荐答案

如果使用动态添加元素,则需要将元素委托给静态父元素 on()
试试这个

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);  
  });

然而将其委托给最近的静态父(在插入时出现)比文件本身更好..所以,如果你在 main_category_field div ..中添加列表,那么你可以使用

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

这篇关于将onclick事件应用于页面加载时不存在的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆