我解决了旧问题,因为这是我的第二个问题
我还需要知道一件事。如何选择“用户chat_user”的子代?
var anchors = document.getElementsByClassName("user chat_user");
for(var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
anchor.onclick = function() { setTimeout(function() {
var ok = document.getElementsByClassName("user-dropdown")[0];
var za = document.createElement("li");
za.className = "user-dropdown-entry";
za.innerText = "Mention";
ok.append(za);}, 10);
}
}
答案 0 :(得分:0)
您必须确保定义/存在您的元素。
尝试一下:
let ok = document.querySelector(".user-dropdown");
// Ensure the class `.user-dropdown` exists
if (ok) {
// Only loop through how many exist, no more
Array.from(document.getElementsByClassName("user chat_user")).forEach(anchor => {
anchor.onclick = () => {
// Use querySelector to select only the first of child here
let za = document.createElement("li");
za.className = "user-dropdown-entry";
za.innerText = "Mention";
ok.append(za);
}
});
}
.user.chat_user {
border: 1px solid black;
display: inline-block;
}
<dive class="user-dropdown">user dropdown</div>
<ul class="messages">
<li class="chat_msg msg-user-message">
<div class="colorbar user"></div>
<span class="user chat_user">
<span class="chat_user_prof">
<img src="https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/e8/e852c40b62be21a16b9f6d69a584e742d7364abb.jpg"></span>
<span class="xp_70">
<i class="icon"></i>
<span class="level_val">79</span>
</span>
<a class="chat_user_name">ChickenİX * 1</a>
<span class="chat_user_ico">
<i class="icon-gammdom-symbol"></i>
<span class="chat_user_colen">:</span>
</span>
</span>
<span class="chat_cont">İg diyon xd</span>
</li>
</ul>