jquery var仅定义第一个元素

时间:2014-06-08 06:40:16

标签: jquery html variables

我有一个jquery var的问题,我很困惑.. 由于变量“id”,我创建了一个var,但它仅影响第一个元素:

jQuery的:

var butInfo = $(".but > div").attr("id");

$("#" + butInfo).each(function(){
    $(this)
        .mouseenter(function(){
            $(".txt").hide();
            $(".txt."+butInfo).show();})
        .mouseleave(function(){
            $(".txt."+butInfo).hide();});
});

HTML:

<div class="but">
    <div id="a">A</div>
    <div id="b">B</div>
    <div id="c">C</div>
</div>
<div class="txt a">A A A A A</div>
<div class="txt b">B B B B B</div>
<div class="txt c">C C C C C</div>

http://jsfiddle.net/74FYW/

如您所见,只有第一个div id="a"正在运行,而其余的仍无法正常工作。 为什么会这样?!!

更新 ========== 我终于找到了我想要的东西。 解决方案只是将jquery函数之后的var行放在它之前;

这就是我的意思:

$(".but > div").each(function(){
  var butInfo = $(this).attr("id"); 
  $(this)
    .mouseenter(function(){
      $(".txt").hide();
      $(".txt."+butInfo).show();
    })
    .mouseleave(function(){
      $(".txt."+butInfo).hide();
    });
});

JSFiddle Demo:

4 个答案:

答案 0 :(得分:3)

attr从匹配的集合中获取第一个元素的属性。尝试这样的事情:

var $txt = $(".txt").hide();
$(".but > div").mouseenter(function() {
    $txt.hide().filter('.' + this.id).show();
})
.mouseleave(function () {
    $txt.hide();
});

演示:http://jsfiddle.net/74FYW/1/

答案 1 :(得分:0)

你可以使用它,但这不是令人难以置信的方式

     $(".but > div").mouseenter(function() {
            var index=$('.but div').index(this);
            $('.txt:eq('+index+')').show();
        }).mouseleave(function () {
    $('.txt').hide();
});

答案 2 :(得分:0)

谢谢你们,但我终于找到了我想要的东西。 解决方案就是将var行放在jquery函数中而不是它之前;

这就是我的意思:

$(".but > div").each(function(){
  var butInfo = $(this).attr("id"); 
  $(this)
    .mouseenter(function(){
      $(".txt").hide();
      $(".txt."+butInfo).show();
    })
    .mouseleave(function(){
      $(".txt."+butInfo).hide();
    });
});

JSFiddle Demo:

答案 3 :(得分:0)

if (this.value > '0') {
var ya1 = $('#' + this.value + 'yap1').val();
$('#yap1').val(ya1);
相关问题