简体   繁体   中英

JavaScript - Concatenating 2 parameters inside a function not working

I am trying to parse 2 numbers as parameters of the function saveQuestion function but it is not working.

$("#questionRow")
.append('<input type="submit" class="btn btn-default" id="saveQuestion'
        + addSectionCount + '" value="Save question ' 
        + addSectionCount + '" onclick="saveQuestion(' 
        + addOpSectionCount + '\',\'' addSectionCount + ')" ></div>');

It would be far less brittle and avoid the problem altogether if you just used jQuery to register a proper callback function instead of using '90s style inline event handlers:

$('<input type="submit" />')
    .attr('id', 'saveQuestion' + addSectionCount)
    .val('Save question ' + addSectionCount)
    .on('click', function() {
        saveQuestion(addOpSectionCount, addSectionCount);
    })
    .appendTo('#questionRow')'

Note also the other uses of jQuery functions to avoid the use of string concatenation within the HTML string.

NB: I've reversed the append so that the chained .on call applies to the newly created element, not to #questionRow .

NB 2: I'd normally use $('<el>', {id: ..., val: ...}) but ISTR that MSIE has (had?) an issue with that syntax on input elements.

It seems you missed a + operator near the end of your code

$("#questionRow")
    .append('<input type="submit" class="btn btn-default" id="saveQuestion'
        + addSectionCount + '" value="Save question ' 
        + addSectionCount + '" onclick="saveQuestion(' 
        + addOpSectionCount + '\',\''
        + addSectionCount + ')" ></div>');

As Luca mentioned, you were missing a + operator. You also didn't add enough single quotes into saveQuestion's arguments for the way you formatted it. This should work:

$("#questionRow")
   .append('<input type="submit" class="btn btn-default" id="saveQuestion'
       + addSectionCount + '" value="Save question ' 
       + addSectionCount + '" onclick="saveQuestion(\'' 
       + addOpSectionCount + '\',\'' + addSectionCount + '\')" ></div>');
   });

As others have mentioned, since you're using jQuery anyway, you should attach a click event handler to the input using jQuery:

$('#saveQuestion'+addSectionCount).on('click', function() {
   // do stuff
});

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