首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >jQuery替换了元素id,但以后无法识别

jQuery替换了元素id,但以后无法识别
EN

Stack Overflow用户
提问于 2010-10-09 02:41:25
回答 5查看 197关注 0票数 1

我有一个播放按钮,还有一个前进按钮。

HTML是这样的:

代码语言:javascript
复制
<div id="control">
    <a href="#" id="pause"></a>
    <a href="#" id="next"></a>
</div>

我想要的是,当有人点击暂停时,播放图标就会出现,当他们点击播放时,暂停图标就会再次出现。现在,这可以通过切换来完成,但我也需要播放图标出现时,有人点击下一步,暂停图标出现时,他们点击播放图标。切换对此不起作用。

这是我的jQuery,很明显,由于javascript的性质,它不能工作。(添加的属性play无法识别)

对于我正在尝试做的事情,什么是一个好的解决方案?

代码语言:javascript
复制
// Play/pause is clicked, alternate between starting and stopping the interval 

$('#pause').click(function(event) {
    $(this).css("background-image", "url(../images/controls_play.png)");
    $(this).attr('id', 'play');
});

$('#play').click(function(event) {
    $(this).css("background-image", "url(../images/controls_pause.png)");
    $(this).attr('id', 'pause');
});


$('#next').click(function(event) {
    $('#pause').css("background-image", "url(../images/controls_play.png)");
    $('#pause').attr('id', 'play'); 
});
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2010-10-09 02:45:48

我认为当您更改ID、尝试活动或委托时,点击事件不会被附加

代码语言:javascript
复制
$('#pause').live("click", function(event) {
    $(this).css("background-image", "url(../images/controls_play.png)");
    $(this).attr('id', 'play');
});

$('#play').live("click",function(event) {
    $(this).css("background-image", "url(../images/controls_pause.png)");
    $(this).attr('id', 'pause');
});


$('#next').live("click",function(event) {
    $('#pause').css("background-image", "url(../images/controls_play.png)");
    $('#pause').attr('id', 'play'); 
});
票数 2
EN

Stack Overflow用户

发布于 2010-10-09 02:44:50

您可以使用.delegate()作为播放/暂停处理程序,如下所示:

代码语言:javascript
复制
$('#control').delegate("#pause", "click", function(event) {
    $(this).css("background-image", "url(../images/controls_play.png)")
           .attr('id', 'play');
}).delegate("#play", "click", function(event) {
    $(this).css("background-image", "url(../images/controls_pause.png)")
           .attr('id', 'pause');
});

You can test it out here。现在,不是在页面加载时查找具有匹配ID的控件,而是侦听click事件并在事件发生时检查ID,这将为您提供所需的操作更改效果。请注意,这比.live()更有效,因为您确切地知道元素的位置。

票数 3
EN

Stack Overflow用户

发布于 2010-10-09 02:45:02

点击函数(‘.live’,.live(){});

代码语言:javascript
复制
$('#pause').live('click', function(event) {
    $(this).css("background-image", "url(../images/controls_play.png)");
    $(this).attr('id', 'play');
});

您可以尝试另一种方法。将事件绑定到一个类,然后更改id。然后在做任何事情之前测试id。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3893371

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档