我有一个DJANGO应用程序,希望在JAVASCRIPT中获得文本的值(当它被选中时),但未被定义。
我的代码:
<div class="askedDiv">
{% for i in recentlyUsed %}
<p onclick="myFunction()" id="myBtn">{{i}}</p>
{% endfor %}
</div>
在JS:
function myFunction() {
const x = document.getElementById("myBtn").value;
console.log(x)
}
但在控制台中,我得到未定义的。
当从recentlyUsed列表中选择时,我如何获得不同的文本名称。
3条答案
按热度按时间kyks70gy1#
如果你想要文本,那么只需将所需的值作为参数传递给函数,而不需要使用DOM方法来获取它:
如果您仍然需要该元素,也可以传递它:
一个二个一个一个
hm2xizp92#
试试这个:
html
Js
6yt4nkrj3#
我还没有在本地测试过这种方法。您可以执行下面的操作
其他信息:你的代码不起作用的原因是因为段落元素没有value属性。Value属性只对输入起作用,因为它们的属性是用来设置/获取值的。