[英]How to pass JavaScript variable from Django-object in html template?
Here, I'm trying to convert the text to speech from django object and sorry to say that I don't know basic Js.在这里,我试图将文本从 django object 转换为语音,很抱歉我不知道基本的 Js。 Here is what I've tried.
这是我尝试过的。
Code代码
HTML HTML
<p class="mb-1">{{ obj.reply }}</p>
<button class="btn btn-dark" onclick="txttospeech(obj.reply)">listen</button>
js js
function txttospeech(txt) {
var utterance = new SpeechSynthesisUtterance();
utterance.text = txt;
speechSynthesis.speak(utterance);
}
If you are trying to pass value of reply
attribute to txttospeech
function then you should do like this:如果您尝试将
reply
属性的值传递给txttospeech
function 那么您应该这样做:
<button class="btn btn-dark" onclick="txttospeech({{ obj.reply }})">listen</button>
And if you want to cross verify whether value is actually getting passed.如果你想交叉验证价值是否真的被传递了。 Then you can log in browser's console
然后就可以登录浏览器的控制台了
function txttospeech(txt) {
console.log("Value of reply attribute",txt);
var utterance = new SpeechSynthesisUtterance();
utterance.text = txt;
speechSynthesis.speak(utterance);
}
you can replace onclick
event with addEventListener
, the following will get text from previous element or <p>
as parameter for the .speak()
您可以将
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.