4

如果段落包含“已记录时间:”的措辞,您如何将类动态分配给段落(通过 javascript/CSS)?

您会注意到我已经手动为该段落分配了 class class="dyncontent"

但是,我想将此类动态分配给任何包含“记录时间:”字样的段落标签。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<link href="css.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script type="text/javascript">
if (document.all || document.getElementById){ //if IE4 or NS6+
document.write('<style type="text/css">')
document.write('.dyncontent{display:none;}')
document.write('</style>')
}
</script>
<div class="right">
<ul>
<li class="say agent public">
<p>Description line 1</p>
<p class="dyncontent">Time Recorded: 5MIN(S)</p>
<p>Another description line</p>
</li>
</ul>
</div>
</body>
</html>
4

4 回答 4

3

你可以使用 jQuery:

 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
 <script>
 $(function(){
      $("p:contains('Time Recorded:')").addClass('dyncontents');
 });
 </script>
于 2012-09-19T21:41:59.737 回答
1

$("p").each(function(ele) {if (this.html().indexOf('TimeRecorded') > 1) {$(this).addClass('dyncontent'))}});

于 2012-09-19T21:42:30.597 回答
1

我会做 indexOf 因为它会比 innerText 更容易匹配

var allP = document.getElementsByTagName('p'),
    pLength = allP.length;
while(pLength--){
    if(allP[pLength].innerHTML.indexOf('Time Recorded') != -1){
    allP[pLength].addClass('dycontents');
    }
}

解释一下:首先你得到<p>文档中的所有内容。然后你遍历它们。如果其中任何一个包含 Time Recorded 的文本,则将您的课程添加到其中。

于 2012-09-19T21:47:53.487 回答
-1

以下是没有 Jquery 的解决方案

o = document.getElementsByTagName('p');

    for (i = 0; i < o.length; i++) {
        if (o[i].innerText.indexOf('Time Recorded:') != -1) {
        o[i].className = 'theClassYouWant'; 
        }
    }
于 2012-09-19T21:42:09.597 回答