我怎样才能将所选的每个角色存储到变量中? JS

时间:2017-04-20 13:52:05

标签: javascript arrays variables

完整的Html代码:

<script src="/Resources/jquery-3.1.1.js"></script>
<script src="/Resources/JQueryPlugins/Ease.js"></script>
<script type="text/javascript">
    function codeAddress() {
        // Gathers String Content
        var el = document.querySelectorAll(".con-1");

        // Stores text, and prepares it for use
        var myString = el[0].textContent;   

        // Sets a blank array ready to store myString characters at certain positions
        var matchedIndexes = [];

        // Main function, Gathers characters W,T,M,P in myString
        // As long as (I) has a lower value than myStrings length it keeps searching for characters
        for (var i = 0; i < myString.length; i++) {
            // Gathers characters W T M P
            if (myString[i] == "W" || myString[i] == "T" || myString[i] == "M" || myString[i] == "P") {
                matchedIndexes.push(new myMatch(myString[i], i));
            }
        }

        console.log(matchedIndexes);

        function myMatch(position, character) {
            // Writes to console the position of the character
            this.position = position;

            // Writes to console the character that was collected
            this.character = character;
        }
    }

    // When the window is loaded call codeAddress function
    window.onload = codeAddress;
</script>
<div class="pro-1">
    <div class="con-1 noselect">Welcome To My Playground</div>
    <div class="sod-1 noselect">Stuff Happens Here.</div>
</div>

指出具体问题

// Main function, Gathers characters W,T,M,P in myString
// As long as (I) has a lower value than myStrings length it keeps searching for characters
for (var i = 0; i < myString.length; i++) {
    // Gathers characters W T M P
    if (myString[i] == "W" || myString[i] == "T" || myString[i] == "M" || myString[i] == "P") {
        matchedIndexes.push(new myMatch(myString[i], i));
    }
}

我希望将 W T M P 字符存储到变量中。

最好是一个变量,但我可以使用多个变量。

我不知道如何将它们设置为变量。

2 个答案:

答案 0 :(得分:0)

扩展变量:

$somestring='';
for (var i = 0; i < myString.length; i++) {
    $somestring+=myString[i];
}
console.log($somestring);

答案 1 :(得分:0)

根据您的评论 ;

您已将这些字母收集到变量(数组)中 - matchedIndexes

不幸的是,你想要做的事情(使用display:none隐藏每个角色)无法以你希望的方式实现。其中每个都是字符串中的字符 - 而不是元素。实现此目的的一种方法是从字符串中删除字符并将其放回到div中,就像这样;

if (myString[i] != "W" || myString[i] != "T" || myString[i] != "M" || myString[i] != "P") {
    matchedIndexes.push(new myMatch(myString[i], i));
}

var text = matchedIndexes.toString();
document.getElementsByClassName(".sod-1")[0].innerHTML = text;