【问题标题】:passing parameter to javascript onclick function将参数传递给javascript onclick函数
【发布时间】:2014-01-02 08:49:06
【问题描述】:

我在从 javascript onClick 函数获取参数时遇到问题

title = "as"
$('<li onClick=pushRight('+hello+') class="item"></li>')

我的控制台日志打印出这个 Uncaught SyntaxError: Unexpected token }

【问题讨论】:

  • 为什么不为那个元素设置一个jQuery 事件处理程序呢?

标签: javascript jquery


【解决方案1】:

请不要使用内联js(在你的html中使用onlick)。

在此处查看不使用内联 js 的原因: https://www.google.com/search?q=Why+is+inline+js+bad%3F

这是使用 jQuery 的正确方法:

var $myElem = $('<li class="item"></li>');
$myElem.click(function() {
  pushRight('hello');
});

即使没有 jQuery,它也很容易:

var myElem = document.createElement('li');
myElem.className = 'item';
myElem.addEventListener('click', function() {
  pushRight('hello');
});

现场演示:http://jsbin.com/uDURojOY/1/edit

【讨论】:

    【解决方案2】:

    试试这个方法:

    hello = 'anything';
    $('<li onClick=pushRight("'+hello+'") class="item"></li>')
    

    【讨论】:

      【解决方案3】:
      title = "as"
      $('<li onClick="pushRight("'+hello+'")" class="item"></li>')
      

      查看添加的双引号。 "'+hello+'" 还要在 pushRight 函数上加上双引号。

      您的代码将无法运行,因为它会呈现如下所示的无效 html。

      <li onClick=pushRight(as) class="item"></li>
      

      看,pushRight 之前和之后没有引号,你的之前和之后也是如此 字符串"sa"。知道错误并改正。不推荐使用内联js和html,这些场景需要绑定事件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-16
        • 2017-02-05
        • 2020-04-26
        • 2012-04-26
        • 2011-10-02
        • 2016-01-16
        相关资源
        最近更新 更多