JS推送阵列不工作

时间:2017-12-01 00:19:59

标签: javascript

知道为什么这不会把TFW推到列表中。 TFW是从一个可以正常工作的文本框输入的,但它不会将其推送到列表中。

我无法将代码放入,因为StackOverflow对它的代码有多疯狂。

function tfw() {
    var goodTrump = [
        "america",
        "americans",
        "white people",
        "african americans",
        "black people",
        "blacks",
        "whites",
        "latinos",
        "latinas",
        "mexicans",
        "church",
        "christianity",
        "god",
        "jesus",
        "church and state",
        "trump",
        "money"
    ];
    var badTrump = [
        "mexico",
        "immigration",
        "muslims",
        "islamic terrorist",
        "terrorist",
        "islam",
        "democrats",
        "dexter"
    ];
    var sadTrump = [
        "death",
        "no money",
        "abortion",
        "public school system",
        "public schools"
    ];
    var done = [

    ];
    var TFW = document.getElementById("TFW").value
    for (i = 0; i < done.length; i++) {
        console.log(done[i]);
    }
    if (TFW == "") {
        document.getElementById("image").innerHTML = "<img src='http://inthesetimes.com/images/articles/trump_flicker_face_yess.jpg'><br> Cant react to something not there.";
    } else if (badTrump.indexOf(TFW) !== -1) {
        document.getElementById("image").innerHTML = "<img src='http://inthesetimes.com/images/articles/trump_flicker_face_yess.jpg'>";
    } else if (goodTrump.indexOf(TFW) !== -1) {
        document.getElementById("image").innerHTML = "<img src='http://noiimages.s3.amazonaws.com/images/redstate/20160614-1525871659.jpg'>";
    } else if (sadTrump.indexOf(TFW) !== -1) {
        document.getElementById("image").innerHTML = "<img src='http://www.mintpressnews.com/wp-content/uploads/2016/08/1033209603.jpg'>";
    } else {
        var failsafe = Math.floor(Math.random() * 3);
        if (failsafe === 0) {
            document.getElementById("image").innerHTML = "<img src='http://inthesetimes.com/images/articles/trump_flicker_face_yess.jpg'>";
            goodTrump.push(TFW);
        } else if (failsafe === 1) {
            document.getElementById("image").innerHTML = "<img src='http://noiimages.s3.amazonaws.com/images/redstate/20160614-1525871659.jpg'>";
            badTrump.push(TFW);
        } else {
            document.getElementById("image").innerHTML = "<img src='http://www.mintpressnews.com/wp-content/uploads/2016/08/1033209603.jpg'>";
            sadTrump.push(TFW);
        }
    }
}

任何人都知道问题是什么?

1 个答案:

答案 0 :(得分:0)

您使用此代码定义了TFW,但.value不是函数。如果你记录TFW的值,它现在可能是未定义的,这就是你无法将它推送到数组的原因

你可能会想到jQuery函数.val()会返回id为TFW的div的内容

var TFW = $("#TFW").val();

或者,有一个纯粹的JavaScript解决方案。如果#TFW没有嵌套元素,则可以使用.innerHTML

var TFW = document.getElementById("TFW").innerHTML