我希望在执行Play函数时停止页面跳转到#soundEvent所在页面的顶部。根据这个答案,https://stackoverflow.com/a/1998717/511438 ,它是由 .html()
和 .append()
引起的;可以通过使用 e.preventDefault() 或返回 false(false 不起作用)来阻止页面“跳转”。如何使用preventDefault?
我的文档中有以下内容。准备就绪
$("[data-play-sound]").each(
function ()
{
var soundFile = $(this).attr('data-play-sound');
if (soundFile != "") Play(soundFile);
$(this).removeAttr('data-play-sound');
}
);
function Play(mp3Path)
{
$("#sound_").remove();
console.groupCollapsed(' ');
$('#soundEvent').append('<embed id="sound_" autostart="true" hidden="true" src="' + mp3Path + '" type="audio/mpeg" />');
console.groupEnd();
}
我已经尝试过此操作,但导致错误:对象“0”没有方法 PreventDefault
$("[data-play-sound]").each(
function (e)
{
...
if (soundFile != "") Play(e, soundFile);
...
}
);
function Play(e, mp3Path)
{
e.preventDefault();
...
}
最佳答案
jQuery .each()接受参数索引和值,而不是事件,因此 0
表示索引
关于javascript - 如何添加 e.preventDefault(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15240035/