Javascript JQuery找不到td
我对Javascript/jQuery非常陌生,所以请耐心听我说 我在这里设置了一个JSFIDLE: 正如您在注释中看到的,在下一列中查找div的多次尝试都失败了 代码如下:Javascript JQuery找不到td,javascript,jquery,html-table,next,Javascript,Jquery,Html Table,Next,我对Javascript/jQuery非常陌生,所以请耐心听我说 我在这里设置了一个JSFIDLE: 正如您在注释中看到的,在下一列中查找div的多次尝试都失败了 代码如下: <table> <tr id="testtr"> <td id="fail"> <select class="part_number" id="part_select_from_blanks" name="part_number">
<table>
<tr id="testtr">
<td id="fail">
<select class="part_number" id="part_select_from_blanks" name="part_number">
<option value="">Select a Part</option>
<option desc="Dr. Orion Dickinson" value="32">Alice Wyman</option>
<option desc="Fabiola Harvey" value="31">Camryn Tillman</option>
</select>
</td>
<td id="fail2">
<div id="desc_from_blank2" class="testclass">test</div>
</td>
</tr>
和Javascript在这里:
$('.part_number').change(function () {
var sel = $("option:selected", this);
var desc = sel.attr('desc');
alert(desc);
//alert($('.part_number option:selected').attr('desc'));
// This one finds the div correctly
alert($('#desc_from_blank2').attr('id'));
// This one only finds the div if I remove the <table> from html
alert($(this).next().attr('id'));
// this one never finds the div
alert($(this).next("div").attr('id'));
// This one never finds the div
alert($(this).next().find('.testclass').html());
// This works when I delete <table> from html, but not with <table>
$(this).next().html(desc);
alert($(this).next().html());
});
像这样使用它
alert($(this).closest("td").next().find('.testclass').html());
因为testclass在另一个td中。因此,您需要首先获取父级,然后选择下一个将获取下一个td的。然后你就可以找到div了
这样不行吗
alert($('.testclass').html());
您没有正确选择正确的元素。如果每行上只有一个select和testclass结果字段,则可以这样做:
alert(
$(this) // select
.closest('tr') // parent table row
.find('.testclass') // search for the div with testclass class
.html() // get the HTML contents
.trim() // remove any unnecessary whitespace from either end
);
如果每行有多个,可以执行以下操作:
$(this).closest('td').next().find('.testclass').html().trim();
下一步查找元素的下一个同级
因此,当您使用$this时,您告诉您搜索与.testClass元素具有相同父元素的元素。没有与您正在查找的内容匹配的元素。您需要使用parent或closest向上移动树以查找所需的元素。我怀疑您希望使用该方法查找包含触发更改事件的select元素的td,然后从中使用next获取第二列。像这样:
var secondTd = $(this).closest('td').next();
var secondTd = $(this).closest('td').next();