简体   繁体   中英

Pass string variable to JavaScript function

I'm trying to pass a string value to button onclick event but javascript function not reading anything from variable x

<button class="btn btn-buy" onclick="myFunction(@item.ProductId.ToString())" style="@btnstyle"><h4>Add to Basket</h4></button>

How do I pass variable values to Java script parameter ?

   <script>
            function myFunction(x) {
                 alertify.prompt('Prompt Title', x, '1'
                    , function (evt, value)
                    {

                    }
                    , function () { 
                    alertify.error('Cancel') });
            }
        </script>

It looks as though you just need to put the value in quotes, razor will put the value of @item.ProductId.ToString() directly into the html, but it won't be in quotes, so when the browser interprets it as javascript it will be rather confused.

It's helpful to remember when you're working with razor that it's a templating system which outputs a document which will then be interpreted by the browser. @item.ProductId.ToString() just puts some text into that template. Javascript has no access to that variable, except as it is made available through the template. For this reason, it needs to be surrounded by something to make javascript treat it as a string. Practically this means surrounding it with quotes, as in "@item.ProductId.ToString()"

As an example:

 function myFunction(x) { console.log(x) alertify.prompt('Prompt Title', x, '1', function(evt, value) { }, function() { alertify.error('Cancel') }); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/alertify.js/0.5.0/alertify.min.js"></script> <button class="btn btn-buy" onclick="myFunction('test')" style="@btnstyle"><h4>Add to Basket</h4></button> 

In that example if 'test' were not surrounded by quotes, it'd be undefined, as it's looking for a variable named test:

 function myFunction(x) { console.log(x) alertify.prompt('Prompt Title', x, '1', function(evt, value) { }, function() { alertify.error('Cancel') }); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/alertify.js/0.5.0/alertify.min.js"></script> <button class="btn btn-buy" onclick="myFunction(test)" style="@btnstyle"><h4>Add to Basket</h4></button> 

假设@item.ProductId.ToString()你想调用JS的toString()方法,那么你需要调用.toString以小写T,而不是资本T

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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