如何使用jQuery设置span元素的内部HTML

Ber*_*aki 1 javascript jquery

以下给出了错误Uncaught SyntaxError:意外的标识符:

$('span.xtro').html('');
$('span.xtro').html('<input type='button' class='newbutton send' value='Send request' onclick= 
                      "javascript:request('send','1','2');'>');
Run Code Online (Sandbox Code Playgroud)

我怎么能纠正这个?

Ben*_*rth 10

你没有逃避单引号:

$('span.xtro').html('<input type="button" class="newbutton send" value="Send request"'
                  + ' onclick="request(\'send\',\'1\',\'2\');">');
Run Code Online (Sandbox Code Playgroud)

你也可以摆脱第一个$('span.xtro').html('');,你不应该需要它.

  • @Rob W:20美元说,由于他的问题得到解答,他再也不会看到这个页面了. (3认同)

got*_*itz 5

这不是使用jQuery的最佳方式...不建议使用onclick属性.这是另一种选择

//note wrapping with double quotes and using single ones inside 
var $el = $( "<input type='button' class='newbutton send' value='Send request'>" );
$el.on( 'click', function(){ request('send','1','2'); } ); 
$('span.xtro').html('').append( $el );
Run Code Online (Sandbox Code Playgroud)

EDIT将$ el.bind更改为$ el.on,这是现在使用的