简体   繁体   English

为什么我的代码中val()返回的值是空的?

[英]Why is the value returned by val() in my code empty?

I tried to change the UI for an open dialog box from displaying the list of files to open from inside a select box to a table with 2 columns. 我试图将打开对话框的UI从显示要从选择框内部打开的文件列表更改为包含2列的表。

original code: 原始代码:

JSP JSP

<select size="15" id="options" class="dialog-pane-right"></select>

javascript JavaScript的

for (var index = 0; index < length; index++) {
        var page = data[index];   //data: data to be listed inside select box
        var id = page.id || page;
        var title = page.title || id;

        var $option = $("<option></option>");
        $option.html(title);
        $option.attr("value", id);
}

alerting the choice when clicked on it 单击时提醒选择

choice = $('select#options option');
choice.click(function(){
    alert($(this).val);
});

now I changed the select box to a table like this: 现在我将选择框更改为这样的表:

JSP JSP

<table id="load-opt"></table>

javascript JavaScript的

for(var ind=0; ind<data.length; ind++) {
    //name is the name and desc is the description for each option
    var $option = $("<tr></tr>");
    $option.html("<td>"+name+"</td><td>"+desc+"</td>");
    $option.attr("value", id);
}

alerting the choice when clicked on it 单击时提醒选择

var choice = $('table#load-opt tr td');
choice.click(function(){
    alert($(this.val()); 
});

the former alerts the name of the file I clicked on, but the latter gives an empty alert box. 前者会提示我单击的文件名,而后者会提示一个空的警告框。 Can anyone explain why this is happening? 谁能解释为什么会这样?

The jQuery's val() method is used to get or set the value property of one or more elements. jQuery的val()方法用于获取或设置一个或多个元素的value属性。

In your case, it happens because the HTMLOptionElement ( <option> ) has a value property, and the HTMLTableCellElement ( <td> ) doesn't have one. 在您的情况下,发生这种情况是因为HTMLOptionElement<option> )具有一个value属性,而HTMLTableCellElement<td> )没有一个属性。 You should use .text() instead of .val() , eg: 您应该使用.text()而不是.val() ,例如:

var choice = $('table#load-opt tr td');
choice.click(function(){
    alert($(this.text()); 
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM