在jQuery中调用JavaScript函数会生成<一个href. >

Calling a JavaScript function inside a jQuery generated <a href...>

本文关键字:一个 href jQuery 调用 JavaScript 函数      更新时间:2023-09-26

我对这段代码有一个问题:

$(document).ready(function() {
    $('.notActiveId').change(function() {
        if ($(this).attr('value').length === 0 ) {
            $("#notActiveButton").html('');
        } else {
            $("#notActiveButton").html('<a href="javascript:void(0)" onClick="setStatus(' + $(this).attr('value') + ', activate)" class="operationUnlock" >Activate</a>');
        }
    });
});

我用$(this).attr('value')调用一个名为notActiveId的选择列表中的值。但是问题是如何在setStatus()函数中写$(this).attr('value'),因为我选择的值是这种形式:RZT_83848Rer(所以它由字符,下划线和数字组成)。

如果我试着像上面那样写,那么我得到一个JavaScript错误。

与其使用老式的"onclick",为什么不通过jQuery添加元素呢?

$('#notActiveButton').empty().append($('<a/>', {
  href: '#', // the "javascript:" thing is basically bogus and unnecessary
  click: function () {
    setStatus(this.value, activate);
  },
  class: 'operationUnlock',
  text: 'Activate'
}));

现在,所有这些都假设你的"notActiveButton"元素是<a>标签的某种合法容器。但无论如何,这样你就能写出普通的JavaScript而不用担心引号等问题