[英]Get nearest <p> tag text using JavaScript
Here are the p tags that auto populate on page load with multiple options. 以下是带有多个选项的p标记,这些标记会在页面加载时自动填充。
<div id="bunchOfChoices" class="choices">
{% for user in users %}
<p id="searchOpts" class="searchOpts">{{user.username}}</p>
{% endfor %}</div>
<script>
var opts = document.getElementById('searchOpts');
opts.onclick = function(event) {
var target = event.target || event.srcElement;
the_user = target.innerHTML;
href= "/../users/"+String(the_user);
window.location=href;
};
</script>
This code seems to only get the first "searchOpt". 该代码似乎仅获得第一个“ searchOpt”。 Also, I am aware I can use
<a>
tags instead of this method. 另外,我知道我可以使用
<a>
标记代替此方法。
ID should be unique for one element. ID对于一个元素应该是唯一的。 If you need to categorize multiple p with same name, you can use class and then use below one:
如果您需要对多个具有相同名称的p进行分类,则可以使用class,然后使用以下一个:
document.getElementsByClassName("searchOpts");
Demo: 演示:
console.log(document.getElementsByClassName('searchOpts')[1]);
<p id="searchOpts1" class="searchOpts">Name 1</p> <p id="searchOpts2" class="searchOpts">Name 2</p>
A few things here: 这里有几件事:
Misuse of id
id
滥用
You should never have multiple elements on the page with the same id
. 页面上永远不应有多个具有相同
id
元素。 You should use class
and leave the id
out. 您应该使用
class
并保留id
。
Assigning onclick
handlers: 分配
onclick
处理程序:
You can use the classes to assign onclick
handlers as follows: 您可以使用这些类来分配
onclick
处理程序,如下所示:
<script>
for (let opt of Array.from(document.getElementsByClassName("searchOpts"))) {
opt.onclick = () => {
window.location.href = "/../users/" + opt.textContent;
}
};
</script>
HTML pages should only ever have one element marked with any particular id
. HTML页面仅应具有一个标记有任何特定
id
元素。 Here you are marking all <p>
elements with the id searchOpts
. 在这里,您将所有
<p>
元素标记为id searchOpts
。 This is incorrect. 这是不正确的。
You would be better to remove the id
and just use the class
. 您最好删除
id
并仅使用class
。 Then search for all elements with that class: 然后搜索该类的所有元素:
var allSearchOpts = document.querySelectorAll(".searchOpts");
This returns an element list, so you need to loop over the list to set the click handler on each element. 这将返回一个元素列表,因此您需要遍历该列表以在每个元素上设置单击处理程序。
allSearchOpts.forEach( function(el) {
el.onclick = ...
} );
You are using document.getElementById
this gets the first item with this id. 您正在使用
document.getElementById
它将获得具有此ID的第一项。 when you use IDs the ID name must be unique. 使用ID时,ID名称必须唯一。
If you need to add the event for multi-elements use queryselectorall
and add your event for every item. 如果您需要为多个元素添加事件,请使用
queryselectorall
并为每个项目添加事件。
Try using jQuery, you can get the next p
by using 尝试使用jQuery,您可以通过使用获得下一个
p
$(this).next("p");
in your onclick function. 在您的onclick函数中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.