2015-02-11 55 views
0

我试图根据其联系人(innerHTML)更改<p>背景,但我无法让它工作。innerHTML与JQuery的比较

<head> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> 
<script> 
$(document).ready(function(){ 
    $("button").click(function(){ 
     if ($("p").innerHTML === "just a test"){ 
      $("p").css("background","yellow"); 
     } 
    }); 
}); 
</script> 
</head> 
<body> 

<p>just a test number1</p> 
<p>just a test number2</p> 
<p>just a test</p> 

<button>Execute</button> 

</body> 

我预计只有最后<p>背景改变,但没有任何反应,这是为什么?

+0

请包括小提琴。 – Complexity 2015-02-11 14:37:08

+0

请不要包括小提琴。您可能想使用Stackoverflow片段功能将您的代码转换为现场演示。 – Quentin 2015-02-11 14:43:16

回答

2

jQuery对象上没有innerHTML属性,所以$("p").innerHTML === "just a test"将始终为false

你可以使用.html()代替,但总是从匹配选择第一元素返回数据,所以它仍然会永远false

即使不是这样的话,$("p").css("background","yellow");会设置背景全部的段落。


您需要遍历所有元素并依次测试每个元素。

$(document).ready(function() { 
 
    $("button").click(function() { 
 
    $("p").each(function(index, paragraph) { 
 
     var $p = $(paragraph); 
 
     if ($p.html() === "just a test") { 
 
     $p.css("background", "yellow"); 
 
     } 
 
    }); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p>just a test number1</p> 
 
<p>just a test number2</p> 
 
<p>just a test</p> 
 

 
<button>Execute</button>

0

的innerHTML是一个JavaScript性能,它不属于jQuery的。

您需要更改此:

$("p").innerHTML === "just a test" 

这样:

$("p").html() === "just a test" 

其次选择p是相当大的,expecially你是不是调用它形成任何元素,但在全球范围内。如果可能的话,我会建议使用某种类或id。

第三我会用这样的修复去你algoritm:

$("p").each(function(){ 
    var el = $(this); 
    if(el.htlm() === 'just a test'){ // could change for regexp (bevare of white characters) 
     el.css("background","yellow") 
    } 
}); 

这种方式对于每P元素内的HTML是“只是一个测试”你会改变背景颜色。