调用 Javascript onClick 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17192024/
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-10-27 07:25:43  来源:igfitidea点击:

Call Javascript onClick not working

javascriptasp.net-mvcrazoronclick

提问by Corey Toolis

         *@ JAVASCRIPT
             $(document).ready(function()
             {
             }
             )

             function videochange(url) {
                 alert(url)
             }

On the click of this button it wont hit the JavaScript function above. Any idea why? I really need to get that video.Value to a JavaScript function.....

单击此按钮时,它不会命中上面的 JavaScript 函数。知道为什么吗?我真的需要把那个 video.Value 分配给 JavaScript 函数.....

 @foreach(var video in Model.VideoList)
        {           
            var url = video.Value;
         <input type="button" value="@video.Text" onclick="javascript:videochange(url);" />
            <br />
        }

采纳答案by codingbiz

Try this

试试这个

@foreach(var video in Model.VideoList)
{           
    var url = video.Value;
 <input type="button" value="@v.Value" onclick="@String.Format("videochange('{0}')", url)" />
    <br />
}

回答by Mark Withers

I would use JQuery. Assuming you've got version 1.7 or later, the following code should work. It also enforces a better separation between your markup and your JavaScript.

我会使用 JQuery。假设您拥有 1.7 或更高版本,以下代码应该可以工作。它还强制您的标记和 JavaScript 之间更好地分离。

<div class="container">
  @foreach(var video in Model.VideoList) {           
    <input type="button" value="@video.Text" data-url="@video.Value" />
  }
</div>

<script>
  $(document).ready(function(){
    $('.container').on('click', 'input[type="button"]', function(){
      var url = $(this).attr('data-url');
      alert(url);
    });
  });
</script>

回答by Arun P Johny

Try

尝试

@foreach(var video in Model.VideoList) {           
    <input type="button" value="@video.Text" onclick="videochange('@video.Value');" />
    <br />
}