-3
<table>
    <thead> 
        <tr>
            <th>Name</th>
            <th>Address</th>
        </tr>
    </thead> 
    <tbody>
        <tr>
            <td>Bob</td>
            <td>300 Wacker Drive</td>
        </tr>
    </tbody>
</table>

如果我点击 Bob,我想取回值“Name”。如何使用 jQuery 做到这一点?

4

2 回答 2

4

是的。点击td

var thVal = $(this).closest('table').find('th').eq( this.cellIndex).text();
alert(thVal);
于 2013-07-11T15:17:49.517 回答
0

我做了这个小提琴来模拟对表的 ajax 调用,但我认为这对你来说非常有用 http://jsfiddle.net/ncubica/Umxjb/

在您的情况下,您可以将data-id属性更改为data-name="bob"并请求值$target.attr("data-name")

html

<i style='display:none' id="loadingPopup">Loading</i>
<table>
    <tr>
        <td data-id="td1"> row 1</td>
    </tr>        
   <tr>        
        <td data-id="td2"> row 2</td>
    </tr>
    <tr>
        <td data-id="td3"> row 3</td>
    </tr>        
</table>

JS

$("table").on("click", function(event){
    var $target = $(event.target); 
    if($target.is("td")){
        var id = $target.attr("data-id");
        makeAjax(id);
    }
});

//simulating ajax

function makeAjax(id){
    //you will have to use ajax an retrieve you json format
    //i will simulate ajax only
    $("#loadingPopup").show();
    var _json = { id : id, value : "some value", description : "some description"};
    setTimeout(function(){response(_json)}, 1000);
}

function response(_json){
    $("#loadingPopup").hide();    
    alert(_json.id + " - " + _json.value);
}

CSS

table{font-family:arial; font-size:12px; width:100%}
table tr td{border-bottom:1px solid #CCC; padding:10px; 100%}

编码快乐!!

于 2013-07-11T15:25:06.720 回答