简体   繁体   English

jQuery引用问题与OnClick中的功能

[英]jQuery Quote Issue with Function in OnClick

Here's my code: 这是我的代码:

jQuery("#"+code+"_2").after("<a href='#' id='"+code+"_3' onclick='addfunction('"+code+"', event); return true;'><img src='special.gif' border='0'></a>");

I'm getting a syntax error on addfunction(. The code is a string and I tried wrapping it in quote, but it doesn't work. Any ideas? 我在addfunction(上遇到语法错误。代码是一个字符串,我尝试将其包装在引号中,但不起作用。有什么想法吗?

UPDATE --- This works, but doesn't pass the code and event over in the function. UPDATE ---可以,但是不会在函数中传递代码和事件。

function addfunction() {
alert("THIS WORKS");
}
var myAnchor = $('<a href="#" id="' + code + '_3"><img src="special.gif" border="0"></a>').bind('click', addfunction);
$('#' + code + '_2').after(myAnchor);

您需要转义内部单引号:

jQuery("#"+code+"_2").after("<a href='#' id='"+code+"_3' onclick='addfunction(\'"+code+"\', event); return true;'><img src='special.gif' border='0'></a>");

For the sanity of your mind try to reorganize your code: 为了您的头脑清醒,请尝试重新组织代码:

var insertLink = function(code) {
   var parent = jQuery('#' + code + '_2');
   var a = $('<a/>', {
       href: '#',
       id: code + '_3'
   }).html('<img src='special.gif' border='0'>').on('click', function() {
      addfunction(code, event);
      return true;
   });
}

I haven't tested the code, but you got the point. 我尚未测试代码,但您明白了。

This works! 这可行! Try to avoid the onclick event, use on() instead. 尝试避免onclick事件,请改用on()。

Create the anchor first, bind the click event to it, then append to DOM. 首先创建锚,将click事件绑定到它,然后附加到DOM。

function addfunction(code, event) {
    alert("THIS WORKS, the code is: " + code);
}
var myAnchor = $('<a href="#" id="' + code + '_3"><img src="special.gif" border="0"></a>').bind('click', function(event) {
    addfunction(code, event);
});
$('#' + code + '_2').after(myAnchor);

您的问题是在这里addfunction('"+code+"', event)您需要对onnClick值中的单引号进行转义

jQuery("#"+code+"_2").after("<a href='#' id='"+code+"_3' onclick='addfunction(\'"+code+"\', event); return true;'><img src='special.gif' border='0'></a>");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM