admin管理员组文章数量:1389749
var testStr='World';
tUserBlock.setAttribute('onclick', 'javascript:alert("Hello" + testStr)');
This is probably a dumb question, but I'm trying to add a variable to .setAttribute onclick event, but I'm not quite sure what the correct syntax is to add the variable into the quote? The above alert doesn't show.
var testStr='World';
tUserBlock.setAttribute('onclick', 'javascript:alert("Hello" + testStr)');
This is probably a dumb question, but I'm trying to add a variable to .setAttribute onclick event, but I'm not quite sure what the correct syntax is to add the variable into the quote? The above alert doesn't show.
Share asked Sep 28, 2013 at 12:05 dlofrodlohdlofrodloh 1,7443 gold badges25 silver badges48 bronze badges 1- DO NOT USE SET ATTRIBUTE TO ADD A CLICK HANDLER! BAD BAD BAD. You should be using addEventListener – epascarello Commented Sep 28, 2013 at 12:33
4 Answers
Reset to default 4var testStr='World';
tUserBlock.setAttribute('onclick', 'javascript:alert("Hello '+testStr+'")');
However this is a poor way of binding click events to elements. Instead, look into the element.addEventListener
method - that is the preferred way of binding. There's various reasons for this - one is that you are not limited to just one event of each type (as you are with your current approach). Another is that it keeps code out of your mark-up.
This is the right way of binding events (no need to use setAttribute
):
var testStr='World';
tUserBlock.onclick = function() { alert("Hello" + testStr) };
If you still insist on your original way, this is the way of doing it:
var testStr='World';
tUserBlock.setAttribute('onclick', 'javascript:alert("Hello ' + testStr + '")');
try this.
var testStr='World';
tUserBlock.setAttribute('onclick', 'javascript:alert("Hello '+testStr+'")');
I hope this will help you.
This works for me, and I haven't changed anything:
<button class="tUserBlock">click me</button>
<script>
var tUserBlock = document.querySelector('.tUserBlock');
var testStr='World';
tUserBlock.setAttribute('onclick', 'javascript:alert("Hello" + testStr)');
</script>
本文标签: javascriptHow to add a variable inside a double quoted stringStack Overflow
版权声明:本文标题:javascript - How to add a variable inside a double quoted string - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744651063a2617686.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论