如何使用javascript添加onclick到链接?

时间:2016-07-22 09:21:49

标签: javascript jquery

我正在使用以下代码段将onclick添加到锚标记,但显然它无效。

var address_edit = $('.edit-user a').attr('href'));
$('.edit-user a').prop('onclick', 'Popup("address_edit","Edit","900","500");')

我想要的是什么:

这是我在inspect元素上的代码:

<div class="edit-user">
    <a href="example.com/nokidding">No kidding</a>
</div>

这就是我所需要的:

<div class="edit-user">
    <a onclick='Popup("address_edit","Edit","900","500");' href="example.com/nokidding">No kidding</a>
</div>

6 个答案:

答案 0 :(得分:1)

添加点击事件,如下所示:

$('.edit-user a').click(function(e) {
    e.preventDefault();
    Popup("address_edit","Edit","900","500");

    // I don't know if you need to redirect after popup open
    window.location.href = "example.com/nokidding";
})

答案 1 :(得分:0)

它不是prop,而是attr,因为onclick是属性,而不是属性。但是我会在元素中添加一个带有jQuery的click事件监听器,并在回调中执行你的操作:

$('.edit-user a').click(function(e) {
    // this stops the 'href' of the anchor from being executed
    // if you want the user to follow the 'href' after click, remove the line
    e.preventDefault();

    Popup("address_edit", "Edit", "900", "500");
});

答案 2 :(得分:0)

这不是道具。你可以像这样处理它:

$('.edit-user a').on('click', function() {
    Popup("address_edit", "Edit", "900", "500");
});

答案 3 :(得分:0)

您需要使用动态绑定,因为您正在动态创建元素。使用以下

$(document).on('click', '.edit-user a', function() {
Popup("address_edit", "Edit", "900", "500");
});

答案 4 :(得分:0)

请确认我的演示:

$('.edit-user a').click(function(e) {
    e.preventDefault();
    var href = $(this).attr('href');
    console.log(href);
    //Popup(href, "Edit", "900", "500"); //open popup
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="edit-user">
     <a href="example.com/nokidding">No kidding</a>
 </div>

答案 5 :(得分:0)

这应该有效:)

&#13;
&#13;
$(document).ready(function(e){
$(".link").attr('onclick','Popup("address_edit","Edit","900","500");');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="link" href="example.com/nokidding">No kidding</a>
&#13;
&#13;
&#13;