jquery将内容传递给$(this).text

Nat*_*lia 1 jquery fade

我正在制作一个菜单,在翻转时,链接的文本会发生变化(淡入).我只是从另一个线程复制并粘贴了一段代码

<script type="text/javascript">
    function fade_new_text(){
        $('#what').animate({'opacity': 0}, 500, function () {
            $(this).text('new text');
        }).animate({'opacity': 1}, 500);
    }
    function revert(){
        $('#what').animate({'opacity': 0}, 500, function () {
            $(this).text('do something');
        }).animate({'opacity': 1}, 500);
    }
</script>
Run Code Online (Sandbox Code Playgroud)

然后在身体部分我有菜单本身

<body>
    <a href="#" id="what" onmouseover="fade_new_text();" onmouseout="revert();">Do something</a>
</body>
Run Code Online (Sandbox Code Playgroud)

这适用于一个链接,但我需要创建其中的7个,并希望将来重用此代码.所以我需要将链接ID和新文本传递给Jquery函数以获得6个其他链接,希望来自'onmouseover'和'onmouseout',因为它最有意义吗?我是Jquery的新手,非常感谢您就如何做到这一点的建议.

测试文件位于http://www.voxcommunications.ca/test.html

Bry*_*yan 6

与JofryHS的回答类似,您可以通过利用锚标记上的数据属性以及使用jQuery将多个事件绑定到同一个处理程序这一事实来简化操作.

HTML

<a href="#" class="hoverlink" id="what" data-mouseover="Hovering over what" data-mouseout="Do something">Do something</a>

<a href="#" class="hoverlink" id="what1" data-mouseover="Hovering over what1" data-mouseout="Do something else">Do something else</a>
Run Code Online (Sandbox Code Playgroud)

JS:

$(".hoverlink").bind("mouseover mouseout", function(e) {
    var elem = $(this);
    var text = elem.data(e.type); // e.type will have name of the current event

    elem.animate({"opacity": 0}, 500, function() {
        elem.text(text);
    }).animate({"opacity": 1}, 500);
});
Run Code Online (Sandbox Code Playgroud)

的jsfiddle