我有评论栏及其回复的子块。两者都具有信息块,其具有到用户简档的链接和具有用户姓名的文本值。我创建链接以向用户发送私人消息,但只有在我用数组中的数字标记它时它才有效。
这是html标记:
<div class="comments_list">
<div class="comment_item">
<div class="comment_body">
<div class="info">
<a href="http://test.com/users/test/" class="username">Test</a>
</div>
<p>Some parent text</p>
</div>
<div class="reply_comments">
<div class="comment_body">
<div class="info">
<a href="http://test.com/users/fred/" class="username">Fred</a>
</div>
<p>Some child text</p>
</div>
</div>
</div>
<div class="comment_item">
<div class="comment_body">
<div class="info">
<a href="http://test.com/users/ken/" class="username">Ken</a>
</div>
<p>Another parent text</p>
</div>
<div class="reply_comments">
<div class="comment_body">
<div class="info">
<a href="http://test.com/users/jack/" class="username">Jack</a>
</div>
<p>Another child text</p>
</div>
</div>
</div>
</div>
以下是代码:
var infobars = document.querySelectorAll('.info');
var usernames = document.querySelectorAll('.info > .username');
function clickPm(event) {
event.preventDefault();
alert(window.location.pathname = '/conversation/' + usernames[1].innerHTML);
//alert here to show that username passed properly
}
var newContainer = document.createElement('span');
newContainer.className = 'container';
var newBtn = document.createElement('a');
newBtn.className = 'pmlink';
newBtn.appendChild(document.createTextNode('send message'));
newBtn.href="#";
newBtn.onclick = clickPm;
newContainer.appendChild(newBtn);
infobars[1].appendChild(newBtn);
对不起我的JavaScript知识和新手问题。
希望你能帮助我在没有jQuery的情况下用纯JavaScript解决它。 Demo on JsFiddle
答案 0 :(得分:0)
Array.prototype.forEach.call(infobars, function(el) {
var newContainer = document.createElement('span');
newContainer.className = 'container';
var newBtn = document.createElement('a');
newBtn.className = 'pmlink';
newBtn.appendChild(document.createTextNode('send message'));
newBtn.href="#";
newBtn.onclick = clickPm;
newContainer.appendChild(newBtn);
el.appendChild(newBtn);
});
不完全确定你在这里问的是什么,但我认为这就是你想要的......
答案 1 :(得分:0)
试试这个 的更新强>
function clickPm(event) {
event.preventDefault();
var username = event.target.parentElement.parentElement.querySelector('a.username').innerText;
alert(window.location.pathname = '/conversations/' + username);
}