将链接的属性值复制到输入值onclick

时间:2016-04-26 14:37:26

标签: javascript jquery onclick

我想将链接的属性值val="ok"复制到我的bootstrap模式中的输入字段:

$('#link').on('click', function() {
  var x = document.getElementById("link").getAttribute("val");
  $("#mail").find(".compose").value = x;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a data-toggle="modal" data-target="#mail" id="link" val="ok" class="btn btn-warning btn-flat" title="Mail"><i class="fa fa-envelope"></i>Link</a>
<input class="form-control" placeholder="To:" class="compose" value="" />

1 个答案:

答案 0 :(得分:1)

您应该创建自定义数据属性data-val,然后您可以像yourElem.dataset.val

那样访问它

&#13;
&#13;
var a = document.getElementById('link');
a.addEventListener('click', function() {
  var val = a.dataset.val;
  document.querySelector('.compose').value = val;
})
&#13;
<a data-toggle="modal" data-target="#mail" id="link" data-val="ok" class="btn btn-warning btn-flat" title="Mail"><i class="fa fa-envelope"></i>Link</a>
<input class="form-control compose" placeholder="To:" value="" />
&#13;
&#13;
&#13;

您也可以使用JQuery使用data()

&#13;
&#13;
$('a').click(function() {
  $('input').val($(this).data('val'));
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a data-toggle="modal" data-target="#mail" id="link" data-val="ok" class="btn btn-warning btn-flat" title="Mail"><i class="fa fa-envelope"></i>Link</a>
<input class="form-control compose" placeholder="To:" value="" />
&#13;
&#13;
&#13;