1

如何在以下示例中使用 jquery 更改 css 属性?我需要做的是在用户单击该项目时更改“btn1”类的背景位置。我无法使用“click”功能定位“btn1”类...顺便说一句,我不是专家

<div class="menu">
    <ul>
        <li><a href="#" onclick="loadListaClientes(1);loadClientWeb(1);loadSlideWeb(1);return false;" class="btn1"></a>
        <li><a href="#" onclick="loadListaClientes(2);loadClientGr(1);return false;" class="btn2"></a></li>
        <li><a href="#" onclick="loadListaClientes(3);loadClientAds(1);return false;" class="btn3"></a></li>
        <li><a href="#" onclick="loadListaClientes(4);loadClientPh(1);return false;" class="btn4"></a></li>
        <li><a href="#" onclick="loadListaClientes(5);loadClientMo(1);return false;" class="btn5"></a></li>
        <li><a href="#" onclick="loadListaClientes(6);loadClientApp(1);return false;" class="btn6"></a></li>
       <li><a href="#" onclick="loadListaClientes(7);loadClientId(1);return false;" class="btn7"></a></li>
    </ul>
</div>

ps:我更新了标记

4

3 回答 3

5

像这样试试

$("a.btn1").on("click", function() {
    $(this).css('background-position', 'new_values_here');
});

此外,如果您使用的是列表,则<ul>最好使用它的项目<li>。否则它没有语义意义。

于 2012-12-26T15:44:37.103 回答
0

I did some modifies to your code and now it looks like this

For making this wokring you should load jQuery in your project. I guess this is a good start

于 2012-12-26T16:39:44.653 回答
0

简化 HTML:

<ul class="menu">
    <li><a href="#" class="btn1"></a></li>
    <li><a href="#" class="btn2"></a></li>
    <li><a href="#" class="btn3"></a></li>
    <li><a href="#" class="btn4"></a></li>
    <li><a href="#" class="btn5"></a></li>
    <li><a href="#" class="btn6"></a></li>
    <li><a href="#" class="btn7"></a></li>
</ul>

使用委托添加一键式处理程序:

$(document).ready(function() { // wait for DOM load
    // handle click on menu
    $(".menu").on("click", "a", function(ev) { // delegate to menu div
        ev.preventDefault(); // similar to "return false"
        var button = $(this); // the "a" that was clicked
        var itemIndex = $(button.parent(), ".menu").index() + 1; // calculate element number
        loadListaClientes(itemIndex); // first function can be called using index
        // handle buttons case by case
        switch (itemIndex) {
        case 1:
            // ".btn1" handled here
            button.css('background-position', newPosition); // change background CSS
            loadClientWeb(1);
            loadSlideWeb(1)
            break;
        case 2:
            // ".btn2", etc.
            loadClientGr(1);
            break;
        case 3:
            loadClientAds(1);
            break;
        case 4:
            loadClientPh(1);
            break;
        case 5:
            loadClientMo(1);
            break;
        case 6:
            loadClientApp(1);
            break;
        case 7:
            loadClientId(1);
            break;
        default:
            // default menu action or throw error here
        }
    });
});
于 2012-12-26T17:22:23.427 回答