Jquery选择第一个字母?

Bat*_*fan 16 html javascript jquery query-string

我只是试图让jquery识别一个段落的第一个字母.我该怎么做?

例如,我有一个页面上有一些paragrahs页面.我希望只有以指定字母开头的段落才能被赋予"当前"类,而其他所有段都被隐藏.我非常知道如何添加类并隐藏其他类,但是,我不能让jquery识别第一个字母.

其次,是否可以从url字符串中提取这个"第一个字母"变量?

例如,第1页 - 有一个字母列表.用户点击"B",网址为

http://domain.com/page2.html?letter=b

并且page2获取该变量(b)并将其应用于Jquery,仅显示那些段落

Aar*_*run 21

尝试:

jQuery('p').each(function(){     
    if(jQuery(this).text().substr(0,1).toUpperCase() == 'B'){
         jQuery(this).addClass('someclass')
    }
   })
Run Code Online (Sandbox Code Playgroud)

您可以使用PHP来清理变量并在JS中打印它:

<script type="text/javascript">
var letter = '<?php  echo (strlen($_GET['letter']) == 1) ? $_GET['letter'] : ''; ?>'
</script>
Run Code Online (Sandbox Code Playgroud)

或者只是抓住document.location并提取它.


Bol*_*ock 12

如果您想使用JavaScript letter从URL查询字符串中获取,请在以下位置运行正则表达式window.location.search:

var letterParam = window.location.search.match(/letter=([a-z])/i), letter;

if (letterParam)
{
    letter = letterParam[1];
}
Run Code Online (Sandbox Code Playgroud)

要匹配以该字母开头的段落,请使用charAt()JavaScript字符串中的方法:

if (letter)
{
    $('p').each(function()
    {
        if ($(this).text().charAt(0).toUpperCase() == 'B')
        {
            // Apply the CSS class or change the style...
        }
    });
}
Run Code Online (Sandbox Code Playgroud)


Joh*_*sch 8

要隐藏<p>其文本不以字母开头的标记B:

$('p').filter(function() {
  return $(this).text().charAt(0).toUpperCase() != 'B';
}).hide();
Run Code Online (Sandbox Code Playgroud)


Gab*_*oli 5

$('p').hide().filter(function(){return $(this).text().match(/^b/i);}).show();
Run Code Online (Sandbox Code Playgroud)

或缩进

$('p').hide()
      .filter(
              function(){
                         return $(this).text().match(/^b/i);
                        }
             )
      .show();
Run Code Online (Sandbox Code Playgroud)

i如果你希望它区分大小写,请删除匹配中的..

你可以看看http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html如何获取url参数..