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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10063654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:42:14  来源:igfitidea点击:

How to set inner HTML of a span element using jQuery

javascriptjquery

提问by Beraki

The following gives me the error Uncaught SyntaxError: Unexpected identifier:

以下给了我错误Uncaught SyntaxError: Unexpected identifier

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

How can I correct this?

我该如何纠正?

回答by BenOfTheNorth

You're not escaping the single quotes:

你没有逃避单引号:

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

You can also get rid of the first $('span.xtro').html('');, you shouldn't need it.

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

回答by gotofritz

It's not the best way of using jQuery... onclick attributes are not recommended. here's an alternative

这不是使用 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 );

EDITchanged $el.bind to $el.on which is what is used nowadays

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