如何通过JavaScript变量从django对象在html模板?



在这里,我试图将文本从django对象转换为语音,抱歉地说,我不知道基本的Js。这是我试过的。

HTML

<p class="mb-1">{{ obj.reply }}</p>
<button class="btn btn-dark" onclick="txttospeech(obj.reply)">listen</button>

js

function txttospeech(txt) {
var utterance  = new SpeechSynthesisUtterance();
utterance.text = txt;
speechSynthesis.speak(utterance);
}

如果您试图将reply属性的值传递给txttospeech函数,那么您应该这样做:

<button class="btn btn-dark" onclick="txttospeech({{ obj.reply }})">listen</button>

如果你想交叉验证value是否被传递。然后你可以登录到浏览器的控制台

function txttospeech(txt) {
console.log("Value of reply attribute",txt);
var utterance  = new SpeechSynthesisUtterance();
utterance.text = txt;
speechSynthesis.speak(utterance);
}

您可以将onclick事件替换为addEventListener,以下将从前一个元素或<p>中获取文本作为.speak()的参数

function txttospeech(txt) {
var utterance = new SpeechSynthesisUtterance();
utterance.text = txt;
speechSynthesis.speak(utterance);
}
document.querySelectorAll('button.btn-dark').forEach(function(item) {
item.addEventListener('click', function() {
var textInput = this.previousElementSibling.textContent;
txttospeech(textInput)
})
})
<!--
<p class="mb-1">{{ obj.reply }}</p>
-->
<p class="mb-1">This is speech test</p>
<button class="btn btn-dark">listen</button>
<p class="mb-1">hello world</p>
<button class="btn btn-dark">listen</button>

最新更新