【问题标题】:JQUERY appending a button with onClick event and passing javascript variable in itJQUERY 附加一个带有 onClick 事件的按钮并在其中传递 javascript 变量
【发布时间】:2014-08-14 06:33:42
【问题描述】:
parameters=eval([[\"April\",[[\"medical\",\"1\"],[\"financial\",\"4\"],[\"burial\",\"1\"]]],[\"May\",[[\"medical\",\"2\"],[\"financial\",\"6\"],[\"burial\",\"6\"]]]]);   

<input type="submit" value="Pie Chart" onClick="showChart('<?php echo $title;?>',parameters,'#container','chart','Pie Chart')"/>

当我只是将它包含到我的 html 代码中时,它可以正常工作。 但我想使用 javascript 或 jquery 将其附加到特定的 div 中。像这样。

<script>
    parameter=eval("[[\"April\",[[\"medical\",\"1\"],[\"financial\",\"4\"],[\"burial\",\"1\"]]],[\"May\",[[\"medical\",\"2\"],[\"financial\",\"6\"],[\"burial\",\"6\"]]]]");

    myButton="<input type="submit" value="Pie Chart" onClick="showChart('<?php echo $title;?>',parameters,'#container','chart','Pie Chart')"/>";
    $('#content').append(myButton);
</script>

我的问题是,每当我单击按钮时它都不会执行该功能。也许是因为我传递了可变参数,我的问题是我怎样才能正确地做到这一点?而且我避免使用 ajax,因为它会影响我的大部分代码。

【问题讨论】:

  • 永远不要使用 - eval - stackoverflow.com/questions/86513/…
  • 我使用 eval 将返回的 json-encode 转换为 javascript 对象。它以 hmtl 方式工作,所以在脚本中我不应该使用它?
  • 是的,你不应该使用 JSON.parse

标签: javascript php jquery append json


【解决方案1】:

试试这个:使用转义字符并使用加号运算符添加参数变量

<script>
    parameter=eval("[[\"April\",[[\"medical\",\"1\"],[\"financial\",\"4\"],[\"burial\",\"1\"]]],[\"May\",[[\"medical\",\"2\"],[\"financial\",\"6\"],[\"burial\",\"6\"]]]]");

    myButton="<input type=\"submit\" value=\"Pie Chart\" onClick=\"showChart('<?php echo $title;?>',"+parameters+",'#container','chart','Pie Chart')\"/>";
    $('#content').append(myButton);
</script>

【讨论】:

    【解决方案2】:
    jQuery('#yourbutton').on('click', function() {           
       });  // your on click event
      //to add content to innerhtml of div:
      jQuery('#divelementorother').html(jQuery('#divelementorother').html() +   YourDataToInside);
    

    首先,您会看到 jQuery 的 .on 函数来获取单击事件处理程序以执行函数。您可以将其作为 JavaScript 附加到 div 的 html 中,因此您不必使用按钮本身的 onclick

    其次,要扩展元素的 innerhtml 或 html like ,您必须使用 .html(data) 。或者,我在我的帖子上方看到:您可以使用 append。

    问候

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 2023-03-30
      • 2018-06-24
      • 2016-07-04
      • 1970-01-01
      • 1970-01-01
      • 2017-06-10
      相关资源
      最近更新 更多