【问题标题】:how can pass values from one function to an HTML callback?如何将值从一个函数传递到 HTML 回调?
【发布时间】:2015-11-26 11:40:09
【问题描述】:
var sno=10;
row.insertCell(6).innerHTML="input type='button' value='edit' onclick='editRecord('sno');'";

我想将sno 值传递给另一个函数。

function editRecord(mySno){}

【问题讨论】:

  • 呃,editRecord(sno)?
  • 试试editRecord(sno)
  • 您可以将其分配给变量var variable=sno,然后将variable 传递给其他函数
  • 实际上是全局变量,它每行都会增加..我尝试 editRecord(sno) 但它需要全局变量值(最后一行值)@Andy
  • @ZainFarooq dafuq 真的吗?这没有意义^^

标签: javascript dom


【解决方案1】:

尽量不要混用代码。

创建 HTML 元素

var newRow = row.insertCell(6),
      input = document.createElement('input');

此方法不仅比字符串 innerHTML 更快,它还允许您将输入作为 JavaScript 对象处理。

input.type = 'button';
input.value = 'edit';
input.onclick = editRecord;

你已经创建了一个新行,但是如果你没有创建一个新行,你可以清除行内的代码:

newRow = (function clearHtmlElement (el){
    var newEl = el.cloneNode();
    el.parentNode.replaceChild(newEl, el);
    return newEl;
}(newRow));

最后将输入附加到行元素:

newRow.appendChild(input);

在 HTML 元素范围内保存您的价值

然后你就可以使用属性来保存你的值了:

input.dataset.sno = 10;

input.setAttribute('data-sno', 10);

或者您可以将其保存到 HTML 元素中:

input.sno = 10;

在你的函数中使用你的价值

function editRecord () {
    var sno = this.sno
           || this.getAttribute('data-snow')
           || this.dataset.snow;
    ...
}

选择你的方式来使用它或像我在这里一样使用它们。现在您的函数中有 sno 可用,更重要的是,它可以是您想要的 JavaScript 对象


更新:适应功能的使用

如果您想使用问题中定义的函数,则必须在定义 onclick 处理程序时执行此技巧:

input.onclick = (function(){
    var mySno = sno;
    return function(){
        editR(mySno);
    };
}());

在这里,使用范围,mySno 将在您每次定义 onclick 处理程序时保存对 sno 值的引用。但是这不适用于对象,所以只有数字或字符串可以工作......而且它有点难看。

【讨论】:

    【解决方案2】:

    //当sno为整数时
    var sno=10;
    row.insertCell(6).innerHTML="input type='button' value='edit' onclick='editRecord(" + sno + ");'";

    //当sno是一个字符时
    var sno='C';
    row.insertCell(6).innerHTML="input type='button' value='edit' onclick='editRecord(\'"+ sno +"\');'";

    【讨论】:

      【解决方案3】:

      editRecord('sno'); 正在传递字符串 'sno',您需要像这样传递变量:editRecord(sno);

      【讨论】:

      • 它不起作用...实际是全局变量,逐行增加,它给出最后一行值
      【解决方案4】:

      使用我为你写的下面一行:

      代码

      var sno=10;
          row.insertCell(6).innerHTML="input type='button' value='edit' onclick='editRecord(\'"+sno+"\');'";
      

      【讨论】:

      • 它不工作错误:未捕获的语法错误意外令牌
      • 去掉两个斜杠后试试()
      【解决方案5】:

      您永远不能在双季铵盐中使用双季铵盐或在单只中使用单季铵盐。 这不是真的。 "xxxxx"yyyyy"xxxx" 您可以使用 “xxxxx'yyyyy'xxxxx” 要么 "xxxxx\"yyyyy\"xxxx" 要么 "xxxx"+"yyyyy"+"xxxx"

      var sno=10; row.insertCell(6).innerHTML="input type='button' value='edit' onclick='editRecord('+sno+');'";

      【讨论】:

        【解决方案6】:

        您已经通过这一行传递它:onclick='editRecord(sno);'

        只需从 sno 中删除 '。

        【讨论】:

          猜你喜欢
          • 2021-08-14
          • 2020-09-26
          • 1970-01-01
          • 2021-02-16
          • 2021-10-26
          • 1970-01-01
          • 1970-01-01
          • 2014-04-27
          相关资源
          最近更新 更多