使用Javascript更改HTML标记

时间:2017-05-21 20:03:36

标签: javascript html

我要求用户选择给定的电子邮件,并在点击时从表单中获取javascript。

如果我有像

这样的href
<a href="#" id="myHref" emails="whatever@example.com"></a>

对于从数据库中获取的每封电子邮件,我都有一堆复选框

使用javascript,如何将此value添加到电子邮件中=&#34;&#34;单击复选框标记?

2 个答案:

答案 0 :(得分:0)

您可以为每个复选框收听change事件,以跟踪已检查的电子邮件:

&#13;
&#13;
var boxes = document.querySelectorAll('input[name=email]');
var link = document.getElementById('myHref');
var emails = [];

boxes.forEach(box => box.addEventListener('change', function(e) {
  var v = e.target.value;
  if (e.target.checked === true) {
    if (!emails.includes(v)) emails.push(v);
  } else {
    emails.splice(emails.indexOf(v), 1);
  };
  link.setAttribute('emails', emails.join(', '));
  console.log(link.attributes.emails.value)
})) 
&#13;
<input type="checkbox" value="1@d.com" name="email">
<input type="checkbox" value="2@d.com" name="email">
<input type="checkbox" value="3@d.com" name="email">

<a href="#" id="myHref" emails="whatever@example.com">Link</a>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以在复选框上设置click事件。

&#13;
&#13;
            var arr_el = document.getElementsByClassName('check-boxes');
            for(var i = 0; i < arr_el.length; i++){
                arr_el[i].addEventListener('click', function(){
                    var el = document.getElementById('myHref');
                    var emails = el.getAttribute('emails');
                    var userSelectedEmail = this.value;
                    if(this.checked){
                        el.setAttribute('emails', emails + ';' + userSelectedEmail);
                    } else {
                        // debugger;
                        emails = emails.split(';');
                        var index = emails.indexOf(userSelectedEmail);
                        emails.splice(index, 1);
                        el.setAttribute('emails', emails.join(';'));
                    }
                    document.getElementById('emails').innerText = el.getAttribute('emails');
                });
            }
&#13;
<html>
    <head>

    </head>
    <body>
        <a id="myHref" href="#" emails="test@email.com">Link</a>
        <br>
        <input class="check-boxes" type="checkbox" value="email2@gmail.com">email2@gmail.com<br>
        <input class="check-boxes" type="checkbox" value="email3@gmail.com">email3@gmail.com<br>
        <input class="check-boxes" type="checkbox" value="email4@gmail.com">email4@gmail.com<br>
        <input class="check-boxes" type="checkbox" value="email5@gmail.com">email5@gmail.com<br>

        <p id="emails"></p>
    </body>
</html>
&#13;
&#13;
&#13;