最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Multiple Parameters in button alert? - Stack Overflow

programmeradmin2浏览0评论

I want to make a button that can pass parameters but as you can see where I give the parameter "Jason" to it, it ends the line for the 'onclick' value. What should I do?

<script type="text/javascript">
    function greeting(name,age){
        alert("Hello, "+name+", you are "+age+" years old.");
    }
</script>
<form>
<input type="button" value="Click me" onclick="greeting("Jason",20)" />

I want to make a button that can pass parameters but as you can see where I give the parameter "Jason" to it, it ends the line for the 'onclick' value. What should I do?

<script type="text/javascript">
    function greeting(name,age){
        alert("Hello, "+name+", you are "+age+" years old.");
    }
</script>
<form>
<input type="button" value="Click me" onclick="greeting("Jason",20)" />
Share Improve this question edited Dec 7, 2018 at 6:42 Cœur 38.8k25 gold badges206 silver badges278 bronze badges asked Feb 27, 2013 at 2:01 user1869879user1869879 171 silver badge3 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

Use single quotes inside double quotes, otherwise you're terminating the string:

onclick="greeting('Jason',20)"
                 -^-   -^-

You need to use different quotes.

<input type="button" value="Click me" onclick="greeting('Jason',20)" />

Or you can use HTML entities.

<input type="button" value="Click me" onclick="greeting(&quot;Jason&quot;,20)" />

But onclick is pretty antiquated. I'd do something like this.

HTML:

<button type="button" class="js-greeting" data-name="Jason" data-age="20">Click me</button>

JS (plus jQuery; you can do it without, but cross-browser issues still make it gross):

$(function() {
    $('.js-greeting').click(function() {
        var name = $(this).data('name');
        var age = $(this).data('age');

        alert("Hello, " + name + "; you are " + age + " years old.");
    });
});
发布评论

评论列表(0)

  1. 暂无评论