我遇到一段代码问题,当点击一个字体真棒音量图标时,它会播放一个短的mp3 / ogg文件。 HTML工作正常。问题在于js代码
<p id="pathVar">/templates/beez_20/audio/dialogs/buy_flowers/</p>
<div id="dialog">
<div id="title_block">Buying flowers </div>
<div id="dlg_container">
<div id="audio_player" >{audio}Buying flowers|dialogs/buying_flowers/buying_flowers.mp3{/audio}</div>
<p class="dlg_content eng_dlg"><span class="dlg_text" id="bf01">Shopkeeper: Good afternoon, how can I help you?</span> <span class ="fa fa-volume-up fa-volume-up-dlg"></span> </p>
<p class="dlg_content eng_dlg"><span class="dlg_text">สวัสดีตอนบ่าย,มีอะไรให้ฉันช่วยไหม?</span></p>
...
</div></div>
js code
jQuery.noConflict();
jQuery(document).ready(function() {
jQuery("div#dlg_container").on("click",function (evnt) {
var elementId = evnt.target.id,
pathVar = document.getElementById("pathVar").innerHTML,
oggVar = pathVar+elementId+".ogg",
mp3Var = pathVar+elementId+".mp3",
audioElement = document.createElement("audio");
audioElement.src = Modernizr.audio.ogg ? oggVar : mp3Var;
audioElement.load();
audioElement.play();
});
});
Firebug显示elementId变量为nil,而在上面的例子中它应该包含“bf01”。我不明白为什么会出现这种情况,因为其他地方的类似代码也可以。我想我在这里遗漏了一些明显的东西。提前感谢您的帮助。
答案 0 :(得分:1)
问题可能是点击源的实际元素可能没有id。因此,假设所有span.dlg_text
元素都有一个ID,并且您希望能够点击p.dlg_content
元素中的任何位置,请尝试
jQuery.noConflict();
jQuery(function ($) {
$("#dlg_container").on("click", 'p.dlg_content', function (evnt) {
var elementId = $(this).find('.dlg_text').attr('id'),
pathVar = document.getElementById("pathVar").innerHTML,
oggVar = pathVar + elementId + ".ogg",
mp3Var = pathVar + elementId + ".mp3",
audioElement = document.createElement("audio");
audioElement.src = Modernizr.audio.ogg ? oggVar : mp3Var;
audioElement.load();
audioElement.play();
});
});
答案 1 :(得分:0)
您正在将一个click事件附加到父容器,该容器有许多具有id属性的div。因此,根据您的示例,如果您单击 {audio}购买鲜花|对话框/ buying_flowers / buying_flowers.mp3 {/ audio elementID将为 audio_player
同样,如果您点击&gt;店主:下午好,我该如何帮助您? elementID将 bf01
因此,如果您想将点击事件附加到“bf01”,只需将click事件附加到该特定div。
jQuery("#bf01").on("click",function (evnt) {
var elementId = evnt.target.id,
pathVar = document.getElementById("pathVar").innerHTML,
oggVar = pathVar+elementId+".ogg",
mp3Var = pathVar+elementId+".mp3",
audioElement = document.createElement("audio");
audioElement.src = Modernizr.audio.ogg ? oggVar : mp3Var;
audioElement.load();
audioElement.play();
});
答案 2 :(得分:0)
还可以将onClick()事件添加到html元素,以便触发javascript函数:
<强> HTML 强>
<div id="dlg_container" onClick="play_sound('some_defined_event')"></div>
JS功能:
function play_sound(evnt) {
var elementId = evnt.target.id,
pathVar = document.getElementById("pathVar").innerHTML,
oggVar = pathVar+elementId+".ogg",
mp3Var = pathVar+elementId+".mp3",
audioElement = document.createElement("audio");
audioElement.src = Modernizr.audio.ogg ? oggVar : mp3Var;
audioElement.load();
audioElement.play();
};