下面的脚本是当按下按钮时,浏览器说出可变词。但是,我在laravel刀片中使用@foreach
。因此,唯一的第一个按钮有效。但是foreach生成的其余按钮不起作用。
index.blade.php
@foreach($data as $val)
<h2><a class="word" href="/?keyword={{$val->word}}">{{$val->word}}</a></h2>
<input id="text" type="hidden" value="{{$val->word}}">
<button id="speak-btn">play</button>
@endforeach
<script>
const text = document.querySelector('#text')
const speakBtn = document.querySelector('#speak-btn')
speakBtn.addEventListener('click', function() {
const uttr = new SpeechSynthesisUtterance(text.value)
speechSynthesis.speak(uttr)
})
</script>
那么如何使所有按钮正常工作?我想我需要在JavaScript中使用this
。但是,我是JS的新手,我不知道如何正确使用它。谢谢。
如果您要生成多个按钮,则它们不应都具有相同的ID。
您应该改用类。
@foreach($data as $val)
<h2><a class="word" href="/?keyword={{$val->word}}">{{$val->word}}</a></h2>
<input class="text" type="hidden" value="{{$val->word}}">
<button class="speak-btn">play</button>
@endforeach
并且您想使用选择器.speak-btn
查询按钮,然后在它们上循环。
我在这里使用的方法有些笨拙,但是尝试遵循您的逻辑以使其更易于理解。
<script>
const speakBtns = document.querySelector('.speak-btn')
speakBtns.forEach(function(speakBtn, index) {
speakBtn.addEventListener('click', (function(index) {
return function() {
const text = document.querySelector('.text')[index]
const uttr = new SpeechSynthesisUtterance(text.value)
speechSynthesis.speak(uttr)
}
})(index))
}
</script>
您不能为所有按钮使用相同的ID,您可以使用相同的类并按类进行查询,也可以调用一个函数并在其中传递文本并进行播放
@foreach($data as $val)
<h2><a class="word" href="/?keyword={{$val->word}}">{{$val->word}}</a></h2>
<input id="text" type="hidden" value="{{$val->word}}">
<button class="speak-btn" onclick="play('{{$val->word}}')">play</button>
@endforeach
<script>
function play(text) {
// Change these 2 lines if you need
const uttr = new SpeechSynthesisUtterance(text)
speechSynthesis.speak(uttr)
}
</script>