javascript - 在 ASP.NET 页面中调用多个 jQuery 函数

标签 javascript asp.net jquery coding-style

我有一个页面,其中包含三个 HTML 标签及其对应的包含在 div 中的 ASP.NET GridView 。现在在学习 jQuery 的同时,我正在努力实现两件事:
1. 更改鼠标悬停/离开时标签的 css 类。
2. 在点击标签时向上/向下滑动网格 div。
它看起来像预期的那样工作,但我想知道我是否以正确的方式进行。

我完整的 jQuery 代码是:

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

我从标签控件的 onmouseover、onmouseout 和 onclick 事件调用这些函数,将标签 ID 作为参数传递。例如:

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

请告诉我这是否是实现这些效果的最佳方式?我不必在 jQuery 代码中正确设置文档就绪函数吗?

非常感谢!

最佳答案

标准的 jQuery 风格是将所有 jQuery 函数绑定(bind)到文档就绪中,正如您在问题中已经猜到的那样。

所以代替

<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,你可以绑定(bind)到 hover文档中的事件准备就绪,方式与我在上面的点击事件中展示的方式相同。

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

关于javascript - 在 ASP.NET 页面中调用多个 jQuery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3491758/

相关文章:

JavaScript:蛇梯游戏中的问题

javascript - 重定向并执行 javascript

javascript - 状态没有正确增加reactjs

c# - iFrame IE8 使用 jQuery ColorBox

javascript - Jquery UI 可调整大小不适用于 ckeditor

jquery - 带有 jquery 动画的圆圈文本

javascript - 如何在 HTML 属性内的函数调用中将变量作为参数传递?

asp.net - 创建 .NET Core Web 开发时(在 .NET Framework 上运行)是什么?

c# - 如何使用 DDay.iCal 创建 Outlook "appointment"?

jquery - 带有 Bootstrap 开关的 Bootstrap glyphicon