我有一个页面,其中包含三个HTML标签以及它们包含在div中的相应ASP.NET gridviews。现在,在学习jQuery的同时,我试图实现两件事:
1.鼠标悬停/移出时,更改标签的css类。
2.单击标签时上下滑动网格div。
它看起来工作正常,但是我想知道我是否做对了。

我完整的jQuery代码是:

$(function ColorChange(ID) {
                $("#" + ID).toggleClass("gridLabel");
});
$(function ShowHide(GID) {
                $('#' + GID).slideToggle('slow');
});


我从标签控件作为参数传递标签控件的onmouseover,onmouseout和onclick事件中调用这些函数。举个例子:

<label id="lblWebComp" class="gridLabelDefault" onmouseover="ColorChange('lblWebComp')"
                onmouseout="ColorChange('lblWebComp')" onclick="ShowHide('gvDivWC')">
                Web Components
</label>


请让我知道这是否是达到这些效果的最佳方法?我是否不必纠正jQuery代码中的文档准备功能?

非常感谢!

最佳答案

标准jQuery样式是将jQuery中的所有函数绑定到文档中,就像您在问题中已经猜到的那样。

所以代替

<label id="lblWebComp" class="gridLabelDefault" onmouseover="ColorChange('lblWebComp')"
                onmouseout="ColorChange('lblWebComp')" onclick="ShowHide('gvDivWC')">


在html标记中,您可能只是

<label class="gridLabelDefault">


然后在jQuery中:

$(document).ready(function() {
    $('.gridLabelDefault').click(function() { // this assigns the click to all elements with gridLabelDefault class
        // here you want to find which grid the clicked label corresponds to, as an example
        // I've used siblings, which you could use if your elements are within a shared parent div
        $(this).siblings('.grid').slideToggle('slow'); // assuming you grid has a 'grid' class
    });
});


希望这应该使您对应针对的代码结构有所了解,显然您需要根据需求进行调整。 jQuery documentation通常很好。

关于css切换,我从您的示例中并未真正看到在jQuery中这样做有什么好处。只需使用hover选择器并在css文件中进行即可。但是,如果您确实要使用jQuery,则可以按照与上述click事件所示相同的方式绑定到文档中的hover事件。

$('.gridLabelDefault').hover(
    function () { // this is the mouseOver function
        $(this).addClass('gridLabel');
    },
    function () { // this is the mouseOut function
        $(this).removeClass('gridLabel');
    }
);

07-24 18:43
查看更多