Jquery $(this)选择器

时间:2013-03-17 15:30:38

标签: php jquery

我正在学习jQuery,我有这段代码:

 echo "<table border=1>                 
    <tr><th class='col1'>Mã Sinh Viên <a href='javascript:void(0)' data-page='$page' data-field='stuId' data-sort='$sort' data-key='$key'><img src='downArrow.gif'></a></th>
        <th class='col2'>Họ tên <a href='javascript:void(0)' data-page='$page' data-field='stuName' data-sort='$sort' data-key='$key'><img src='downArrow.gif'></a></th>
        <th class='col3'>Ngày sinh  <a href='javascript:void(0)' data-page='$page' data-field='stuDoB' data-sort='$sort' data-key='$key'><img src='downArrow.gif'></a></th>
        <th class='col4'>Giới tính <a href='javascript:void(0)' data-page='$page' data-field='stuSex' data-sort='$sort' data-key='$key'><img src='downArrow.gif'></a></th>
        <th class='col5'>Địa chỉ <a href='javascript:void(0)' data-page='$page' data-field='stuAdd' data-sort='$sort' data-key='$key'><img src='downArrow.gif'></a></th>
    </tr>
";

还有一些剧本:

$("#mainTable th a").click(function()   {
    var clicked= $(this);
    var page= clicked.data("page");
    var field= clicked.data("field");
    var sort= clicked.data("sort");
    var key= clicked.data("key");
    if(sort== 'up') {
        sort= 'down';
        clicked.html("<img src='downArrow.gif'>");
        clicked.attr("data-sort",sort);
    }
    else    { 
        sort= 'up';
        clicked.html("<img src='upArrow.gif'>");
    }
    showPage(page,field,sort,key);
});

我需要的是点击图片时会改变图片。我使用.click事件和$(this)选择器来处理被点击的元素。但是当我点击图片时,它仍然是相同的。

我的代码出了什么问题?我试过 CTRL-ALT-j ,但没有错误。请帮帮我。

3 个答案:

答案 0 :(得分:1)

尝试使用clicked.data("sort",sort);设置data-sort属性

$("#mainTable th a").click( function () { 
    var clicked = $(this);
    var page = clicked.data("page");
    var field = clicked.data("field");
    var sort = clicked.data("sort");
    var key = clicked.data("key");

    if (sort == 'up') {
        sort = 'down';
        clicked.html("<img src='downArrow.gif'>");
    } else {
        sort = 'up';
        clicked.html("<img src='upArrow.gif'>");       
    }
   clicked.data("sort",sort);
});

<强> Working Sample

答案 1 :(得分:0)

你的桌子没有课。

在javascript代码中,您选择带有 mainTable 类的表,但该表不存在...

答案 2 :(得分:0)

尝试通过jQuery选择锚点数据:

$("#mainTable th a").click(function()   {
    var clicked= $(this);
    var page= clicked.attr("data-page");
    var field= clicked.attr("data-field");
    var sort= clicked.attr("data-sort");
    var key= clicked.attr("data-key");
    if(sort== 'up') {
        sort= 'down';
        clicked.html("<img src='downArrow.gif'/>");
        clicked.attr("data-sort",sort);
    }
    else    { 
        sort= 'up';
        clicked.html("<img src='upArrow.gif'/>");
    }
    showPage(page,field,sort,key);
});