简体   繁体   English

传递参数时 JavaScript 不调用函数

[英]JavaScript not calling a function when param is passed

JavaScript is not calling a function when parameter is passed.传递参数时,JavaScript 不会调用函数。

I am creating HTML dynamically.我正在动态创建 HTML。

checkbox2 = document.createElement("<input type=\"checkbox\"  name=\"wdrs_contact\" checked=\"Yes\" onclick =\"setPartnersInfo('\"+id+\"');\" />");

function setPartnersInfo(ch)
{
    alert(ch)
}

But when I do not have parameter in the function call, it is working.但是当我在函数调用中没有参数时,它正在工作。

details below:详情如下:

function createPartnerTable() {

    var partnerInfo = document.getElementById("partnersInfo");
    var data = partnerInfo.value;

    // everything was successful so now come back and update, first clear the old attributes table
    var partnersBody = document.getElementById("partnersBody");
    var rowCount = partnersBody.rows.length;
    for( var i = 0; i < rowCount; i++ )
    {
        partnersBody.deleteRow(0);
    }

    if (data ==null || data.length==0)
        return;

    // now parse and insert each partner row
    //alert("data : "+data);
    var index = 0;
    var lastIndex = 0;
    while( index < data.length && index != -1 )
    {
        lastIndex = data.indexOf("|", index);
        if( lastIndex == -1 ){
            break;
        }

        var id = data.substring(index, lastIndex);

        index = lastIndex + 1;
        lastIndex = data.indexOf("|", index);
        var name = data.substring(index, lastIndex);

        index = lastIndex + 1;
        lastIndex = data.indexOf("|", index);
        var partnerType = data.substring(index, lastIndex);

        index = lastIndex + 1;
        lastIndex = data.indexOf("|", index);
        var status = data.substring(index, lastIndex);

        index = lastIndex + 1;
        lastIndex = data.indexOf(";", index);
        var jdeCode = data.substring(index, lastIndex);

        //ganessin
        index = lastIndex + 1;
        lastIndex = data.indexOf("#", index);
        var wdrsContact = data.substring(index, lastIndex);

        row = partnersBody.insertRow(partnersBody.rows.length);

        //check box with id for removal
        var checkboxCell = row.insertCell(0);
        checkboxCell.align="center";
        var checkbox = document.createElement('<input type="checkbox"  name="selectedPartnerIds" />');
        //var checkbox = document.createElement("input");
        //checkbox.type = 'checkbox';
        //checkbox.checked=false;
        //checkbox.name = 'selectedPartnerIds';
        checkbox.value=id;
        //checkbox.style.align = "center";
        //checkbox.style.width = '40%';
        checkboxCell.appendChild(checkbox);

        var check = document.getElementsByName('selectedPartnerIds');

        //Name
        var nameCell = row.insertCell(1);
        nameCell.appendChild(document.createTextNode(name));

        //Partner Type
        var partnerTypeCell = row.insertCell(2);
        partnerTypeCell.align="center";
        partnerTypeCell.appendChild(document.createTextNode(partnerType));

        //Status
        var statusCell = row.insertCell(3);
        statusCell.align="center";
        statusCell.appendChild(document.createTextNode(status));

        //JDE Code
        var jdeCodeCell = row.insertCell(4);
        jdeCodeCell.align="center";
        jdeCodeCell.appendChild(document.createTextNode(jdeCode));

        //ganessin
        var checkboxCell2 = row.insertCell(5);
        checkboxCell2.align="center";
        var checkbox2 = "";
        //alert("wdrsContact "+wdrsContact);
        var x = "setPartnersInfo("+id+")";
            alert("x = "+x);
        if(wdrsContact == "true")
        {
            alert("true");

            //checkbox2 = document.createElement('<input type="checkbox"  name="wdrs_contact" checked="Yes" onclick="+x+" onchange="+x+" />');
            checkbox2 = document.createElement("<input type=\"checkbox\"  name=\"wdrs_contact\" checked=\"Yes\" onclick =\"setPartnersInfo(\"+id+\");\" />");
            //String(document.createElement('<input type="checkbox"  name="wdrs_contact" checked="Yes" onchange="setPartnersInfo("+id+");"/>'))
        }
        else
        {
            alert("false");
            //checkbox2 = document.createElement('<input type="checkbox"  name="wdrs_contact" onclick="+x+" onchange="+x+" />');
            checkbox2 = document.createElement("<input type=\"checkbox\"  name=\"wdrs_contact\" onclick=\"setPartnersInfo(\"+id+\");\" />");
        }
        //alert("id "+id);
        //checkbox2.value=id;
       // alert("checkbox2 "+checkbox2);
        checkboxCell2.appendChild(checkbox2);

        // increment the index to process next
        index = lastIndex + 1;
    }

}

The following will generate a syntax error:以下将产生语法错误:

"onclick =\"setPartnersInfo('\"+id+\"');\""

You should use:你应该使用:

"onclick =\"setPartnersInfo(\'"+id+"\');\""

Or if your id is numeric (you don't need quotes):或者,如果您的 id 是数字(您不需要引号):

"onclick =\"setPartnersInfo("+id+");\""

If you wish to use double quotes within a html attribute you have to convert them to &quot;如果您希望在 html 属性中使用双引号,则必须将它们转换为&quot;

So the following should work too:所以以下也应该起作用:

"onclick =\"setPartnersInfo(&quot;"+id+"&quot;);\""

Although should isn't really the right word as generating html with event listeners like this is not the best approach.尽管应该不是真正正确的词,因为使用这样的事件侦听器生成 html 并不是最好的方法。

So overall your string should be:所以总的来说你的字符串应该是:

("<input type=\"checkbox\"  name=\"wdrs_contact\" checked=\"Yes\" onclick =\"setPartnersInfo('"+id+"');\" />");

Although to get around the escaping all the time why not use:虽然要一直逃避逃避,为什么不使用:

('<input type="checkbox"  name="wdrs_contact" checked="Yes" onclick ="setPartnersInfo(\''+id+'\');" />');


in the interest of improvement为了改进

The better way to achieve what you are doing is to split your code from your markup, and leave the browser to generate your markup, this is easier to read and tends to be faster - plus it means you don't have to worry so much about escaping quotes ;)实现您正在做的事情的更好方法是将您的代码与您的标记分开,让浏览器生成您的标记,这更容易阅读并且速度更快 - 而且这意味着您不必担心那么多关于转义引号 ;)

checkbox2 = document.createElement('input');
checkbox2.type = 'checkbox';
checkbox2.name = 'wdrs_contact';
checkbox2.checked = 'checked';
checkbox2.onclick = function(){
  setPartnersInfo(id);
}

One major difference to be aware of in the above is that before when you placed your id var in the html string - it's current value was recorded in that string.上面要注意的一个主要区别是,在您将id var 放入 html 字符串之前 - 它的当前值记录在该字符串中。 With the above the reference to the id variable is remembered but not the value .上面的 id 变量的引用被记住,但不是 value If you change the value of id at any point after this, it will still change whereever it is referenced.如果您在此之后的任何时候更改id的值,无论它在哪里被引用,它仍然会更改。 To get around this you can use a closure .为了解决这个问题,您可以使用closure

This works by passing the value of id into a function, which basically changes the variable being used to store your value of id to stored_id , this function then returns a function that is used as your event handler.这是通过将id的值传递给一个函数来工作的,该函数基本上将用于存储id值的变量更改为stored_id ,然后该函数返回一个用作事件处理程序的函数。 This event handler function has access to the stored_id var, and no matter how much you change id , stored_id wont be changed.这个事件处理函数可以访问stored_id var,无论你改变多少idstored_id不会改变。 It's a bit complicated, if you don't know about closures then it's a good topic to read up on.这有点复杂,如果您不了解闭包,那么这是一个值得阅读的好主题。

checkbox2.onclick = (function(stored_id){
  return function(){setPartnersInfo(stored_id);};
})(id);

To improve the above even further you should be avoiding using inline event handlers, so:为了进一步改善上述情况,您应该避免使用内联事件处理程序,因此:

checkbox2 = document.createElement('input');
checkbox2.type = 'checkbox';
checkbox2.name = 'wdrs_contact';
checkbox2.checked = 'checked';
/// for modern browsers
if ( checkbox.addEventListener ) {
  checkbox.addEventListener('click', function(){
    setPartnersInfo('your id here');
  });
}
/// for old ie
else {
  checkbox.attachEvent('onclick', function(){
    setPartnersInfo('your id here');
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM