jquery variable?

jquery variable?

本文关键字:variable jquery      更新时间:2023-09-26

我是jQuery的新手,我编写了以下jQuery,用于在地图上显示特定链接时显示div:

<div id="locationmap">
    <a class="linkhide" id="link1" href="#">Occupier 1</a>
    <a class="linkhide" id="link2" href="#">Occupier 2</a>
    <a class="linkhide" id="link3" href="#">Occupier 3</a>
</div>  
<div id="mapdetail">
    <div class="hideme" id="local1" style="display:none;">
        <p>Some content one</p>
    </div>
    <div class="hideme" id="local2" style="display:none;">
        <p>Some content two</p>
    </div>
    <div class="hideme" id="local3" style="display:none;">
        <p>Some content three</p>
    </div>    
</div>
<script type='text/javascript'>//<![CDATA[
    $("#link1").mouseover(function() { $("#local1").fadeIn(500); });
    $("#link2").mouseover(function() { $("#local2").fadeIn(500); });
    $("#link3").mouseover(function() { $("#local3").fadeIn(500); });
    $(".linkhide").mouseout(function() { $(".hideme").css('display','none'); });
//]]>
</script>

但是,正如您所看到的,.fadeIn(500)正在为每个链接重复。我如何将它作为一个变量,并为每一行调用它?这将节省我为每个链接重复相同代码30次左右的时间。

我这里有一个JSfiddle:http://jsfiddle.net/karlgoldstraw/4NRY7/

谢谢。

function mouseOver(localId) {
    return function() { $("#local" + localId).fadeIn(500); }
}
 $("#link1").mouseover(mouseOver(1));

您可以使用数据属性来简化链接和div之间的连接,,,

<a data-id="2"...
$('a.linkhide').mouseover(function() {
  var el = '#local' + $(this).data('id');
  $(el).fadeIn(500);
});

因为我还没有看到它,所以我想在这里添加我的答案。虽然我意识到上面的答案是完全可行的,但我的解决方案让链接告诉函数要显示的内容是什么。通过添加一个javascript函数来检查链接的哈希值,您可以将其用作选择器来执行渐变。这也会带来降级更好的好处,因为在禁用javascript的情况下,哈希链接仍然会让用户看到正确的内容。

JavaScript

var fade = function(){
    var contentSelector = this.hash;
    $(contentSelector).fadeIn(500);
};

然后声明鼠标悬停:

$("#linkone").mouseover(fade);
$("#linktwo").mouseover(fade);
$("#linkthree").mouseover(fade);
$("#linkfour").mouseover(fade);

或者你甚至可以这样做:

$(".linkhide").mouseover(fade);

然后在HTML 上

<a class="linkhide" id="linkone" href="#content1">Link 1</a>
<a class="linkhide" id="linktwo" href="#content2">Link 2</a>
<a class="linkhide" id="linkthree" href="#content3">Link 3</a>
<a class="linkhide" id="linkfour" href="#content4">Link 4</a>

等等。。。

JSFiddle-http://jsfiddle.net/4NRY7/11/

这是一种不涉及更改HTML的方法。正如您可能知道的那样,更改链接的id可以使此操作更加高效。

$(".linkhide").mouseover(function() {
    var linkDivMap = { 'one' : 1, 'two' : 2, 'three' : 3, 'four' : 4 };
    var contentBox =$(this).attr('id').replace('link','');
    $("#content" + linkDivMap[contentBox] ).fadeIn(500);
});
$(".linkhide").mouseout(function() { $(".hideme").css('display','none'); });

替换当前脚本。

这允许您对所有.linkhide元素使用单个动态函数和单个jQuery.mouseover()调用,以避免@MikeThomsen的回答仍然导致代码重复。

$( document ).ready( function () {
  $( ".linkhide" ).mouseover( function ( event ) {
    var item_id = this.id.match( /([0-9]+)$/ )[1];
    $( "#local" + item_id ).fadeIn( 500 );
  } );

  $( ".linkhide" ).mouseout( function () {
      $( ".hideme" ).css( 'display', 'none' );
  } );
} );