【问题标题】:Any way that I can replace the function variable with javascript?有什么方法可以用javascript替换函数变量吗?
【发布时间】:2009-08-18 05:49:29
【问题描述】:

有谁知道如何用 Javascript 替换 html 中的传递变量?

例子:

如果我有如下代码:

<table width="150" border="0" cellspacing="0" cellpadding="2" id="productBox">
<tr>
    <td valign="top" height="19" id="td4"><img onclick="addNewRowToTable('abc')" src="images/add0.gif" onmouseover="this.src=\'images/add1.gif\'" onmouseout="this.src=\'images/add0.gif\'" class="handCursor" width="49" height="19"></td>
</tr>
</table>

我可以用javascript将变量“abc”替换为“cde”吗?

【问题讨论】:

  • 为什么不把cde传给函数呢?

标签: javascript


【解决方案1】:

可以(正如其他人所指出的那样),但我怀疑如果我们知道您实际上想要做什么,您可能会得到更有用的答案;肯定有更好的方法来解决您的问题,但我需要上下文来暗示它可能是什么。

【讨论】:

    【解决方案2】:

    您可以将全局变量传递给函数。并在代码中将这个变量定义得更高。

    <script>
    var globalVar='cdb';
    </script>
    
    <table width="150" border="0" cellspacing="0" cellpadding="2" id="productBox">
    <tr>
        <td valign="top" height="19" id="td4"><img onclick="addNewRowToTable(globalVar)" src="images/add0.gif" onmouseover="this.src=\'images/add1.gif\'" onmouseout="this.src=\'images/add0.gif\'" class="handCursor" width="49" height="19"></td>
    </tr>
    </table>
    

    如果您稍后更改 globalVar,它将影响您的代码。

    【讨论】:

      【解决方案3】:

      如果你想替换 onclick 属性来调用 addNewRowToTable('cde') 而不是它现在调用的,我建议重新绑定事件:

      var img = // Here you would get the <img> somehow
      img.onclick = function () { addNewRowToTable('cde'); };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-20
        • 1970-01-01
        • 2018-11-04
        • 1970-01-01
        • 2019-01-24
        • 1970-01-01
        • 2019-09-16
        • 1970-01-01
        相关资源
        最近更新 更多