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