如何将点击事件绑定到最近添加的< a>标签在jquery [英] How to bind a click event on a recently added <a> tag in jquery

查看:177
本文介绍了如何将点击事件绑定到最近添加的< a>标签在jquery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面上的6个链接到mp3。

I have 6 links on a page to an mp3.

我安装的插件用swf替换这些链接,并播放mp3 inline。

The plugin I installed replaces those links with a swf and plays that mp3 inline.

的问题是可以激活所有6个链接,并一次播放所有音频。我解决了这个问题(我觉得在一个笨拙的新手方式)通过捕捉<

The problem I had was that it was possible to activate all 6 links and have all audio playing at once. I solved that problem (I feel in a clumsy novice way though) by catching the < a > tag before it was replaced with the embed tag and then putting it back when another one was clicked.

但是,这是我的问题现在:< a> tag我放回丢失它的onClick事件(我认为这是发生了什么),所以,如果再次单击,无法切换像第一次。

However, this is my problem now: the < a > tag I put back looses it's onClick event (i think that's what is happening) and so, if clicked a second time, fails to switch like the first time.

$(".storyplayer a").bind("click", function() {

        // replace the <a> tag from the previous media player installation
        if (previousplayerlocation != null) {$("#" + previousplayerlocation + " .storyplayer").html(graboldcode);}      

        // now remember this installation's <a> tag before it's replaced
        graboldcode = $(this).parent().html();
        // remember where I grabbed this <a> tag from
        previousplayerlocation = $(this).parents("div.storylisting").attr("id");

        // replaces the <a> tag with the media player.
        $(this).media({width: 190,height: 30});
        return false;
    });

我问是否有一种方法可以将点击事件重新分配给if语句?
谢谢!

I am asking if there is a way to re-assign the click event to the "if" statement? Thanks!

推荐答案

使用事件委托 - 这意味着将点击绑定到某个容器,让它处理事件。然后,您可以查询event.target以查看它是否是被点击的锚点,然后您需要行为。

Use event delegation - this means binding the click to some container and let that handle the event. You can then query the event.target to see if it was an anchor that was clicked then do you required behaviour. This is better for a number of reasons.


  1. 减少与元素绑定的事件(性能)


>代码将是像

The code would be something like

$('#someContainer').click( function(ev){

    var $el=$(ev.target);
    if ( $el.is('a') ){
       //do your stuff
    }

});

查看此 post 更多阅读

这篇关于如何将点击事件绑定到最近添加的&lt; a&gt;标签在jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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