4

段落に「TimeRecorded:」という文言が含まれている場合、(javascript / CSSを介して)段落に動的にクラスを割り当てるにはどうすればよいですか?

class class="dyncontent"を使用して段落を手動で割り当てたことに気付くでしょう。

ただし、このクラスを「TimeRecorded:」という単語を含む段落タグに動的に割り当てたいと思います。

<!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

innerTextよりも一致しやすいのでindexOfを実行します

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

説明するために:最初にあなた<p>は文書のすべてを手に入れます。次に、それらをループします。それらのいずれかにTimeRecordedのテキストが含まれている場合は、それにクラスを追加します。

于 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 に答える