django 如何在使用javascript点击文本时动态获取文本值

a5g8bdjr  于 2023-03-20  发布在  Go
关注(0)|答案(3)|浏览(150)

我有一个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列表中选择时,我如何获得不同的文本名称。

kyks70gy

kyks70gy1#

如果你想要文本,那么只需将所需的值作为参数传递给函数,而不需要使用DOM方法来获取它:

<p onclick="myFunction({{i}})" >{{i}}</p>
function myFunction(x) {
  console.log(x)
}

如果您仍然需要该元素,也可以传递它:
一个二个一个一个

hm2xizp9

hm2xizp92#

试试这个:html

<div class="askedDiv">
  {% for i in recentlyUsed %}
    <p onclick="funName(this)">{{i}}</p>
  {% endfor %}
</div>

Js

function funName(e) {
  console.log($(e).text());
}
6yt4nkrj

6yt4nkrj3#

我还没有在本地测试过这种方法。您可以执行下面的操作

// option 1: pass the event object so function is reusable and can be applied to any element

function getValue(e) {
  const value = e.target.innerText; // if you want to get the text value
  // const value = e.target.innerHTML; // if you want to get the markup value
  
  console.log(value);
}

// option 2: use your current code but fix to that paragraph only basd on id selector

function getValue2() {
   const value = document.getElementById('my-btn').innerText;
   
   console.log(value);
}

// option 3: use the document

// as an alternative, you can bind your click even to the document to dynamically get the value of any element in your document
document.addEventListener('click', function(e) {
  const value = e.target?.value || e.target.innerText;
  
  console.log(e.target);
});
<div>
  <p onclick="getValue(event)">Option 1</p>
</div>

<div>
  <p onclick="getValue2()" id="my-btn">Option 2</p>
</div>

<div>
  <p>Option 3</p>
</div>

其他信息:你的代码不起作用的原因是因为段落元素没有value属性。Value属性只对输入起作用,因为它们的属性是用来设置/获取值的。

相关问题