尝试使用 jquery 更改用户填充表的一行仅适用于第一行



所以我正在做一个学校作业,我有几个表格,然后通过jquery函数用数据填充一个表格。表单由用户填写。其中一项任务也是使用户可以单击表格中的一行,该行将其颜色更改为红色,然后通过按表格底部的按钮删除彩色行。

我似乎不能这样做(更改行颜色)。我只能更改第一行(包含标签的行)的颜色,所有其他行在单击它们时都没有响应。我不知道这是否是由于第一行写在.html文件中,其他行是之后使用 jquery 创建的,但我似乎无法启动并运行它。

这是 html:

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
    </script>
</head>
<body>
    <form>
    <p>
    Naslov opravila: <input id="naslov" type="text" name="naslov">
    Vrsta opravila: <input id="vrsta" type="text" name="vrsta">
    Nivo pomembnosti: 
    <select name="nivo" class="nivo">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select>
    <button class="button">Dodaj opravilo</button>
    </form>
    </p>
    <table class="tabela" cellspacing="3" style="text-align:center">
        <thead>
            <tr>
                <th>#</th>
                <th>Opravilo</th>
                <th>Vrsta</th>
                <th>Nujnost</th>
                <th>Datum vnosa</th>
            </tr>
        </thead>
        <tbody id="telo">
        </tbody>
    </table>
    <button id="odstrani">Odstrani</button>
    <script src="script.js"></script>
</body>

这是.js代码:

$('.button').on('click', function(event) {
    var naslov = $('#naslov').val();
    var vrsta = $('#vrsta').val();
    var nivo = $('.nivo option:selected').val();
    var vrste = $('#telo').find('tr').length;
    var datum = new Date();
    var d = datum.getDate() + "." + (datum.getMonth()+1) + "." + datum.getFullYear();
    if(naslov.length > 0) {
        var novavrsta = $('<tr><td></td><td></td><td></td><td></td><td></td></tr>');
        novavrsta.children().eq(0).text(vrste+1);
        novavrsta.children().eq(1).text(naslov);
        novavrsta.children().eq(2).text(vrsta);
        novavrsta.children().eq(3).text(nivo);
        novavrsta.children().eq(4).text(d);
        novavrsta.appendTo('#telo');
        $( "#telo tr" ).addClass(function( index ) {
            return "vrsta" + (index+1);
        });
    }
    return false;
});
$("tr").click(function() {
    $(this).css({"color":"red"});
    $(this).addClass("izbrano");
});

有什么想法吗?

由于你的元素是动态创建的,你应该使用 .on()

$(document).on('click', 'tr', function(){
    $(this).css({"color":"red"});
    $(this).addClass("izbrano");
});

此外,如果您不想更改表标题,请使用选择器:

'tbody tr'

最新更新