我正在尝试创建一个更改事件,因此当用户从下拉列表中选择一个选项时,表格中的相应行会突出显示(通过添加一个类)。
我尝试过两件事...... jQuery和javascript。
这是我的jQuery:
$("#phoneType").change(function() {
if (document.getElementById("optionSelect").value == 2) {
var selectedStatus = parseInt(document.getElementById("optionSelect").value);
$('.clickable-row').removeClass("cra-children-item-selected");
$(this).addClass('cra-children-item-selected');
}
});
请注意,我在前两行使用javascript,因为我一直得到" val()不是函数"错误。
我尝试使用javascript简单地添加/删除类,但它似乎不喜欢我的语法...
document.getElementsByClassName("clickable-row").className = "clickable-row";
document.getElementById(selectedStatus).className = "clickable-row item-selected");
我不明白为什么jQuery不起作用......我有另一个功能完美无缺:
$(".clickable-row").click(function(event) {
console.log($(this).attr('id'));
$('.clickable-row').removeClass("item-selected");
$(this).addClass('item-selected');
});
为什么上面的代码(点击时)有效,但不是我的改变功能?
这是HTML:
<table class="table table-striped table-bordered">
<tr>
<th scope="col">Type</th>
<th scope="col">Number</th>
</tr>
<tr id="1" class="clickable-row">
<td>
Work
</td>
<td>
705-556-6677
</td>
</tr>
<tr id="6" class="clickable-row">
<td>
Cellular phone
</td>
<td>
613-444-7777
</td>
</tr>
</table>
<select name="phoneType" id="phoneType">
<option value="-1">Select</option>
<option value="3">Home</option>
<option value="1">Work</option>
<option value="6">Cellular phone</option>
</select>
答案 0 :(得分:1)
检查一下,它确实有效。
.selected {border: solid 1px #000; background-color:blue;};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-striped table-bordered">
<tr>
<th scope="col">Type</th>
<th scope="col">Number</th>
</tr>
<tr id="tr1" class="clickable-row">
<td>
Work
</td>
<td>
705-556-6677
</td>
</tr>
<tr id="tr6" class="clickable-row">
<td>
Cellular phone
</td>
<td>
613-444-7777
</td>
</tr>
</table>
<select name="phoneType" id="phoneType">
<option value="-1">Select</option>
<option value="3">Home</option>
<option value="1">Work</option>
<option value="6">Cellular phone</option>
</select>
var sliders = [].slice.call(document.getElementsByClassName("sliderControlLi"));
答案 1 :(得分:0)
我强烈建议您不要尝试使用id="1"
作为行ID。请改用HTML5 data attributes:
<tr class="clickable-row" data-id="6">
然后简单的jQuery将选择行:
$("#phoneType").change(function() {
var id = parseInt($(this).val());
var $row = $('.clickable-row[data-id="' + id + '"]');
$('.clickable-row').removeClass("cra-children-item-selected");
if (id > 0) {
$row.addClass('cra-children-item-selected');
}
});
答案 2 :(得分:0)
根据您提供的HTML,似乎条件永远不会成立:
if (document.getElementById("optionSelect").value == 2) {
并且应该参考实际存在的选项值的select元素重写
$("#phoneType").change(function() {
var t = $(this),
tVal = t.val();
if (tVal === '3') {
console.log(tVal);
}
});