How do I concatenate a string with a variable?

前端 未结 5 1398
醉话见心
醉话见心 2020-11-22 16:26

So I am trying to make a string out of a string and a passed variable(which is a number). How do I do that?

I have something like this:

function AddB         


        
5条回答
  •  猫巷女王i
    2020-11-22 17:13

    Your code is correct. Perhaps your problem is that you are not passing an ID to the AddBorder function, or that an element with that ID does not exist. Or you might be running your function before the element in question is accessible through the browser's DOM.

    To identify the first case or determine the cause of the second case, add these as the first lines inside the function:

    alert('ID number: ' + id);
    alert('Return value of gEBI: ' + document.getElementById('horseThumb_' + id));
    

    That will open pop-up windows each time the function is called, with the value of id and the return value of document.getElementById. If you get undefined for the ID number pop-up, you are not passing an argument to the function. If the ID does not exist, you would get your (incorrect?) ID number in the first pop-up but get null in the second.

    The third case would happen if your web page looks like this, trying to run AddBorder while the page is still loading:

    
    My Web Page
    
    
    

    To fix this, put all the code that uses AddBorder inside an onload event handler:

    // Can only have one of these per page
    window.onload = function() {
        ...
        AddBorder(42);
        ...
    } 
    
    // Or can have any number of these on a page
    function doWhatever() {
       ...
       AddBorder(42);
       ...
    }
    
    if(window.addEventListener) window.addEventListener('load', doWhatever, false);
    else window.attachEvent('onload', doWhatever);
    

提交回复
热议问题