我有一个页面,其中包含三个 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/