如何显示Javascript文件中的所有元素

时间:2018-03-13 16:21:01

标签: javascript underscore.js

当我选择正确元素显示的位置时,我想显示从下拉框中选择位置时的所有元素,但是当我选择全部显示所有元素时,不会显示任何元素。

HTML代码:

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="jquery-3.3.1.min.js"></script>
    <script type="text/javascript" src="underscore.js"></script>
    <script type="text/javascript" src="players.js"></script>
    <script type="text/javascript" src="playerFilter.js"></script> 
</head>
<body>

<h1>Players by Position</h1>
<select id="position">
<option value=''>Select...</option>
<option value='All'>All</option>
<option value='Goalkeeper'>Goalkeeper</option>
<option value='Defender'>Defender</option>
<option value='Midfielder'>Midfielder</option>
<option value='Forward'>Forward</option>
</select>
<hr>

<div id="data"></div>

</body>

.JS文件:

window.onload=function()
{

    document.getElementById('position').onchange=function()
    {
        function getPlayerPosition(element)
        {
            if(element.Position == $("#position").val())
             return true;
        }

        var playerPosition = _.filter(players, getPlayerPosition);
        console.log(playerPosition);

        $("#data").html("");
        _.each(playerPosition, function(element){
            $("#data").append(element.Name + "<br>");
        });

    }
}

1 个答案:

答案 0 :(得分:0)

只使用jquery你可以使用[ attribute-not-equal-selector ]选择器1

这样做

$("#position").on('change', function() {
  var str = '';
  if ($(this).val() === "All") {
    var getAllElem = $("#position option").not("[value='All']").not("[value='']").each(function(i, v) {
      str += $(v).text() + ' ';
    })
    $("#data").html(str);
  } else {
    $("#data").html($(this).val());
  }


})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Players by Position</h1>
<select id="position">
        <option value=''>Select...</option>
        <option value='All'>All</option>
        <option value='Goalkeeper'>Goalkeeper</option>
        <option value='Defender'>Defender</option>
        <option value='Midfielder'>Midfielder</option>
        <option value='Forward'>Forward</option>
    </select>
<hr>
<div id="data"></div>