无法设置属性&inner;内部HTML'由于函数

时间:2018-01-01 18:36:04

标签: javascript html

在尝试上传数据时不断出现此错误,继承我的js代码:

displayOutput(data); //this is from ajax

function displayOutput(games)
{

    console.log(games[1]["Genres"]);
    let ul = document.getElementById('ajax');
    let output = "";

    games.forEach(game => {


            output+= "<a href=#><li>" + game["Name"]+"</a></li>";   
            output+= "<li>" + game["Release Date"]+"</li>";         
            output+= "<li>" + game["Genres"]+"</li>";   
            output+= "<li>" + game["Retail Price"]+"</li>";  
            output+= "<li>" + game["Rating"]+"</li>"; 
            output+= "<li>" + game["image"]+"</li>";    
            output += '<li><img src="${game.image}"></li>';
    })
    ul.innerHTML = output;
}

只是想注意,当我添加第一个功能时,一切都很好

但是在重新使用该功能时。那一切都变得疯狂,破坏了原有的功能。原始函数是第一个,然后重新使用它是第二个代码块

1 个答案:

答案 0 :(得分:0)

您想要的是重用相同的功能,而不是重新定义它。这将是代码:

displayOutput(data, id);

function displayOutput(games, elementID)
{
    console.log(games[1]["Genres"]);
    let ul = document.getElementById(elementID);
    let output = "";

    games.forEach(game => {
            output+= "<a href=#><li>" + game["Name"]+"</a></li>";   
            output+= "<li>" + game["Release Date"]+"</li>";         
            output+= "<li>" + game["Genres"]+"</li>";   
            output+= "<li>" + game["Retail Price"]+"</li>";  
            output+= "<li>" + game["Rating"]+"</li>"; 
            output+= "<li>" + game["image"]+"</li>";    
            output += '<li><img src="${game.image}"></li>';
    })
    ul.innerHTML = output;
}

如果要在函数中按页面进行变换,可以在函数内部使用一些内部逻辑来识别它是哪个页面,然后创建适当的输出,或者使用不同的函数处理它。例如:

function displayOutput_userPage(games, elementID)
{
    console.log(games[1]["Genres"]);
    let ul = document.getElementById(elementID);
    let output = "";

    games.forEach(game => {
            output+= "<a href=#><li>" + game["Name"]+"</a></li>";   
            output+= "<li>" + game["Release Date"]+"</li>";         
    })
    ul.innerHTML = output;
}

另一页:

function displayOutput_shoppingCartPage(games, elementID)
{
    console.log(games[1]["Genres"]);
    let ul = document.getElementById(elementID);
    let output = "";

    games.forEach(game => {
            output+= "<a href=#><li>" + game["Name"]+"</a></li>";   
            output+= "<li>" + game["Release Date"]+"</li>";         
            output+= "<li>" + game["Genres"]+"</li>";   
            output+= "<li>" + game["Retail Price"]+"</li>";  
            output+= "<li>" + game["Rating"]+"</li>"; 
            output+= "<li>" + game["image"]+"</li>";    
            output += '<li><img src="${game.image}"></li>';
    })
    ul.innerHTML = output;
}