我正在尝试通过JQuery通过其父属性(数据ID)获取元素的文本,但是,我无法获取它。
这是我到目前为止尝试过的:
function getNum() {
return "1234asd";
}
function show() {
console.log($("tr[data-id="+getNum()+"] > td > label").text());
//Console should print "Text1"
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr data-id="1234asd">
<td>
<label>Text1</label>
</td>
<td>
<label>Text2</label>
</td>
</tr>
<tr data-id="5678fgh">
<td>
<label>Text3</label>
</td>
<td>
<label>Text4</label>
</td>
</tr>
</table>
<button onClick="show()">Click me</button>
我希望代码可以打印Text1
,但是它什么也不打印(空字符串)。
答案 0 :(得分:2)
您可以使用Deepak Singh中提到的方法,也可以使用JQuery的.first()
HTML
<table>
<tr data-id="1234asd">
<td>
<label>Text1</label>
</td>
<td>
<label>Text2</label>
</td>
</tr>
</table>
<button onClick="show()">Click me</button>
JS
function getNum() {
return "1234asd";
}
function show() {
console.log($("tr[data-id="+getNum()+"] td").first().text());
//Console prints "Text1"
}
答案 1 :(得分:0)
您需要调整选择器,就像:
$("tr[data-id="+getNum()+"] td:first label").text()
function getNum() {
return "1234asd";
}
function show() {
console.log($("tr[data-id=" + getNum() + "] td:first label").text());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr data-id="1234asd">
<td>
<label>Text1</label>
</td>
<td>
<label>Text2</label>
</td>
</tr>
<tr data-id="5678fgh">
<td>
<label>Text3</label>
</td>
<td>
<label>Text4</label>
</td>
</tr>
</table>
<button onClick="show()">Click me</button>
答案 2 :(得分:-1)
function getNum() {
return "1234asd";
}
function show() {
console.log($("tr[data-id="+getNum()+"] > td > label").text());
//Console should print "Text1"
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr data-id="1234asd">
<td>
<label>Text1</label>
</td>
<td>
<label>Text2</label>
</td>
</tr>
</table>
<button onClick="show()">Click me</button>