繁体   English   中英

选择与表格行比较的选项

[英]Select option comparing with Table Row

我有这个按钮来附加<Select>但是该选项不应显示表行中已经存在的内容(数学,英语,科学),所以我只需要在<select>选项中显示PE SUBJECT ,我尝试做jQuery中的.each,但我无法将两者进行比较。 我试图使我的表动态。

这是我的示例JSFiddle https://jsfiddle.net/ta73h4ez/16/

<!DOCTYPE html>
<html>
<head>
<script
  src="https://code.jquery.com/jquery-3.3.1.js"
  integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
  crossorigin="anonymous">
</script>
<style>
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {
    background-color: #dddddd;
}
</style>
</head>
<body>
<script>
    $( document ).ready(function() {
        $( "#add" ).click(function() {
            $('tbody').append('<tr><td><select><option value="math">Math</option><option value="English">English</option><option value="Science">Science</option><option value="PE">PE</option></select></td><tr>');
        });
    });
</script>
<h2>HTML Table</h2>

<table>
    <tbody>
        <tr>
            <th>Subject</th>
            <th>Start Time</th>
            <th>End Time</th>
        </tr>
        <tr>
            <td>Math</td>
            <td>8am</td>
            <td>9am</td>
        </tr>
        <tr>
            <td>English</td>
            <td>10am</td>
            <td>1pm</td>
        </tr>
        <tr>
            <td>Science</td>
            <td>1pm</td>
            <td>3pm</td>
        </tr>
    </tbody>
    </table>
        <input type="button" value = "Add Subject" id ="add">
    </body>
</html>

您可以像这样比较:

$('table').find('tr').each(function(){
var td1=$(this).find('td').eq(0).text();
$('select').find('option').each(function(){

 var op = $(this).text();
 if(op==td1)
 {
 $(this).hide();
 }

});
});

这是我的样本JSFiddle jsFiddle

将您的JavaScript函数更改为以下内容。 您可以根据需要优化此代码。

$( document ).ready(function() {
        $( "#add" ).click(function() {
        var options = getOptions();
        var optionsString = "";
        for(var i = 0; i< options.length; i++){
            optionsString += '<option value="'+options[i]+'">'+options[i]+'</option>';
        }
            $('tbody').append('<tr><td><select>'+optionsString +'</select></td><tr>');
        });

        var getOptions = function(){
            var options = ["Math", "English", "Science", "PE"];
          var allRows = $('table').find('tr');
          for(var i=0; i< allRows.length && options.length>0; i++){
            var subjectText = $(allRows[i]).find('td').eq(0).text();
            var index = options.indexOf(subjectText);
            options = options.splice(index, 1);
          }
          return options;
        };
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM