【问题标题】:JQuery only changing first instanceJQuery 只改变第一个实例
【发布时间】:2015-10-07 22:36:50
【问题描述】:

我有一些代码可以找到类名为.tab-content-header 的div 的高度,然后更改该div 内h1 的line-height。它适用于.tab-content-header h1 的第一个实例,但我有几个实例并且想同时更改所有实例的行高。所有这些都应该始终相同。我怎样才能改变我的代码来完成这个?我尝试使用.each(),但事情变得一团糟,无法正常工作。下面是我目前拥有的 JQuery 和 .tab-content-header h1 的一个实例,因此您可以看到标记的样子。

$(window).resize(function() {
    var $tabContentHeader = $('.tab-content-header');
    var $headerLineHeight = $tabContentHeader.height() + 10 + 'px';
    $tabContentHeader.find('h1').css({'line-height': $headerLineHeight});
});

<div class="row tab-content-header">
    <img src="images/content-area/page-header.png" class="img-responsive" alt="a1">
    <h1>Welcome</h1>
</div>

【问题讨论】:

  • 我在这里运行了你的演示,它按预期工作。尝试打开你的控制台,看看你是否遗漏了一些语法或搞砸了。

标签: jquery


【解决方案1】:

这是一份工作副本

http://jsfiddle.net/m330147x/1/

$(window).resize(function() {
    console.log("Start");
    var $tabContentHeader = $('.tab-content-header');
    console.log("Found " + $tabContentHeader.length + " Headers");

    var $headerLineHeight = $tabContentHeader.height() + 10 + 'px';

    var $h1 = $tabContentHeader.find('h1');
    console.log("Found " + $tabContentHeader.length + " h1");
    $h1.css({'line-height': $headerLineHeight});
    console.log("Finish");
});

查看开发者控制台以获取调试信息。它应该可以正常工作。

【讨论】:

    【解决方案2】:

    使用这个。

    $(window).resize(function() {
        $('.tab-content-header > h1').each(function(i, obj) {
            var headerHeight =  $('.tab-content-header').height() + 10;
            obj.style.lineHeight = headerHeight + "px";
        });
    });
    

    查看工作示例:https://jsfiddle.net/g73uv468/

    【讨论】:

      猜你喜欢
      • 2011-11-07
      • 2023-03-08
      • 1970-01-01
      • 2013-10-05
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多