使用Javascript / jQUery

时间:2015-11-19 19:16:23

标签: javascript jquery html css

我试图运行一些自定义脚本,根据h4元素中字符串的长度添加样式类。基本上,如果h4足够长以至于需要2行,我会想要调整CSS,以便带有两行标题的h4也与具有单行标题的h4排成一行。

一些JQuery将所有标记返回其内容..

jQuery(document).ready(function($){
  $('div.post-content div.title-info h4 a').text(function(){
      console.log(this);
  });
});

返回..

<a href=​"http:​/​/​www.theaterunder30.com/​farewell-to-amazing-grace/​">​Farewell to Amazing Grace​</a>​
<a href=​"http:​/​/​www.theaterunder30.com/​details-announced-for-harry-potter-and-the-cursed-child/​">​Details Announced for “Harry Potter and the Cursed Child”​   </a>​
<a href=​"http:​/​/​www.theaterunder30.com/​another-blog-post/​">​Another Blog Post​</a>​
<a href=​"http:​/​/​www.theaterunder30.com/​arrested-development-quotes/​">​Arrested Development Quotes​</a>​

哪个好。但这只是谜题的一部分。我需要能够仅在标签内对字符进行计数,然后使用类似.length的内容来确定它是否大于X字符数量执行{...}

我不确定如何访问标签之间的文字?为了在它上面运行.length。我已经看过这个post,但老实说,我无法弄清楚如何将它应用到我的情况中。任何帮助或指导都会很棒。

感谢您的期待!

3 个答案:

答案 0 :(得分:6)

您想使用jQuery .text()来获取文本:

jQuery(document).ready(function($){
  $('div.post-content div.title-info h4 a').each(function(){
      console.log($(this).text().length);
      //Conditional logic based on text length here
  });
});

答案 1 :(得分:0)

我认为你在寻找:

$(document).ready(function($){
                                         // V-- each not text!
  $('div.post-content div.title-info h4 a').each(function(){
    console.log($(this).text());
  });
});

输出:

  

告别神奇的恩典

     

“哈利波特与被诅咒的孩子”宣布的细节

     

另一篇博文

     

逮捕发展行情

答案 2 :(得分:-1)

检查文本的长度,如果它长于你想要的长度(比如本例中的20个字符),只需添加一个css类。

$('a').each(function(){
    length = $(this).text().length;
    if(length > 20) {
        $(this).addClass('long');
    }
});

你可以看到它正在使用这个JS小提琴:https://jsfiddle.net/9s8evwcx/