我只是尝试让jquery识别段落的第一个字母。我该怎么做呢?
例如,我有一个页面,该页面上有多个别名。我希望只有以指定字母开头的段落才会被赋予"current“类,而所有其他段落都会被隐藏。我很清楚如何添加类并隐藏其他类,但是我不能让jquery识别第一个字母。
其次,是否可以从url字符串中提取'first letter‘变量?
例如,第1页-有一个字母列表。用户单击'B‘,url为
http://domain.com/page2.html?letter=b
page2选择变量(b)并将其应用于Jquery,只显示这些段落
发布于 2010-06-15 01:34:09
尝试:
jQuery('p').each(function(){
if(jQuery(this).text().substr(0,1).toUpperCase() == 'B'){
jQuery(this).addClass('someclass')
}
})
您可以使用PHP清理变量并将其打印到JS中:
<script type="text/javascript">
var letter = '<?php echo (strlen($_GET['letter']) == 1) ? $_GET['letter'] : ''; ?>'
</script>
或者只是使用document.location
抓取并提取它。
发布于 2010-06-15 01:34:25
如果您想使用JavaScript从URL查询字符串中获取letter
,请在window.location.search
上运行正则表达式
var letterParam = window.location.search.match(/letter=([a-z])/i), letter;
if (letterParam)
{
letter = letterParam[1];
}
要匹配以该字母开头的段落,请在JavaScript字符串中使用charAt()
方法:
if (letter)
{
$('p').each(function()
{
if ($(this).text().charAt(0).toUpperCase() == 'B')
{
// Apply the CSS class or change the style...
}
});
}
发布于 2010-06-15 01:39:19
隐藏其文本不以字母B
开头的<p>
标记
$('p').filter(function() {
return $(this).text().charAt(0).toUpperCase() != 'B';
}).hide();
https://stackoverflow.com/questions/3039397
复制相似问题