简体   繁体   中英

JavaScript not calling a function when param is passed

JavaScript is not calling a function when parameter is passed.

I am creating HTML dynamically.

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):

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

If you wish to use double quotes within a html attribute you have to convert them to &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.

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. With the above the reference to the id variable is remembered but not the value . If you change the value of id at any point after this, it will still change whereever it is referenced. To get around this you can use a 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. This event handler function has access to the stored_id var, and no matter how much you change id , stored_id wont be changed. 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');
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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