javascript - 单击时将 html 存储到变量中,从 DOM 中删除并在另一次单击时将其放回原处

标签 javascript jquery html variables

我正在尝试为视频构建一个开/关按钮。我希望它做的事情相当简单:第一次点击时,它会删除视频(而不是停止它),第二次点击时,它将它放回 dom 中。

我想出了一些代码,但它没有按照我想要的方式工作:

$('#on-off').click(function(e) {
    e.preventDefault();
    if (videoContent !== ""){
        var videoContent = $('#video-container').html();
        console.log(videoContent);
            // At this point, the console shows the variable videoContent does contain the content of #video-container.
        $('#video-container').html("");
    }
    else {
        $('#video-container').html(videoContent);
    }
});

第一次点击工作正常,并将 #video-container 的内容存储到 videoContent 中。 但是,第二个不会将 videoContent 的内容放回 #video-container 中。事实上,它删除了 videoContent 的内容。

我确信这是一个很容易解决的问题,只是我无法弄清楚。 谢谢

最佳答案

将变量videoContent放在全局范围内:

var videoContent = '';

$('#on-off').click(function(e) {
    e.preventDefault();
    if (videoContent !== ""){
        videoContent = $('#video-container').html();
        $('#video-container').html("");
    }
    else {
        $('#video-container').html(videoContent);
    }
});

关于javascript - 单击时将 html 存储到变量中,从 DOM 中删除并在另一次单击时将其放回原处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18445815/

相关文章:

Javascript 在某些情况下无法正确加载

html - 如果有 hidden-xs 则应用 CSS 类

javascript - jQuery : How do I get the current id of the element I have clicked on and change it’s name?

javascript - D3 中的国际象棋走法

javascript - 工具提示/悬停中的音频?

javascript - react-navigation:如何根据当前选项卡更改 tabBar 颜色

javascript - 当我想平滑滚动到这些部分时,JQuery 不工作

c# - 类似于 ASP.NET 按钮的 HTML 按钮

javascript - 需要帮助显示设置的动态日期和时间

javascript - 禁用链接的默认行为