.val,但不返回任何值[JQuery]

.val on a specific child not returning any value [JQuery]

本文关键字:JQuery 任何值 返回 val      更新时间:2023-09-26

我在一个.each循环中,试图访问一组行中的特定表单元格(td)。每一行有三个单元格,其中包含Id、Name和Practice类。

代码:

@foreach (var client in ViewBag.ClientList.getDatabase())
    {
        <tr class="ClientRow">
            <td class="Id">@client.Id</td>
            <td class="Name">@client.getClientName</td>
            <td class="Practice">@client.getPracticeID</td>
        </tr>
    }

//一段时间后,当尝试从foreach 访问时

$(".ClientRow").each(function (index) {
var Name = $(this).children(".Name").val();
var ID = $(this).children(".Practice").val();

Name和ID变量似乎总是返回空字符串。

.val()用于检索value属性(这是.attr('value')的快捷方式),并且只能用于支持此类属性的元素(例如<input /><select><textarea>)。

以下是jQuery Docs对val()函数的描述:

.val()方法主要用于获取表单的值例如inputselecttextarea。假使select元素,当未选择任何选项时返回null,并且数组,包含在至少一个,并且可以选择更多,因为multiple属性存在。

要获取元素的innerHTML或文本内容,应使用.text().html()

例如:

$(".ClientRow").each(function (index) {
var Name = $(this).children(".Name").text();
var ID = $(this).children(".Practice").text();

.text()返回元素的实际文本(没有任何HTML)
CCD_ 19将返回该元素的CCD_。

val()用于输入,在您的情况下,您必须使用:

$(".ClientRow").each(function (index) {
var Name = $(this).children(".Name").text();
var ID = $(this).children(".Practice").text();