2012-08-04 145 views
4

我想改變標籤上的紅色按鈕的顏色單擊使用jquery更改標籤的顏色?

但是該代碼是不工作的一切似乎是正確的

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title> 
    </title> 
    <script type="text/javascript"> 
    function changeColor(id, newColor) { 

var labelObject = document.getElementById(id); 

$("#" + id).css("color", newColor); 

} 
    </script> 
</head><body> 
<form id="frm2"> 

<label for="model">Male</label> 

<input type="text" name="cars" id="model" /> 

<br /> 

<label for="female">Female</label> 

<input type="text" name="cars" id="color" /> 

</form> 

<input type="button" value="Change Label Color" onclick="return changeColor('label', 'red')" /> 

    </body> 
</html> 

請幫

+2

其中與在標記LabelCity控制? – Shyju 2012-08-04 14:32:26

回答

9

你」重新傳遞'label'作爲您的changeColor處理程序的id參數,但在您提供的HTML中沒有包含該ID的元素。您需要爲標籤添加一些ID並將其傳遞到onclick處理程序中。例如:

<label for="model" id="label1">Male</label> 
<input type="text" name="cars" id="model" /> 

<input type="button" value="Change Label Color" onclick="return changeColor('label1', 'red')" /> 

另一種方法是傳遞輸入元素的ID,因爲它們已經有ID分配給它們。這樣,你會需要修改changeColor處理程序如下:

function changeColor(inputId, newColor) { 
    $("#" + inputId).prev().css("color", newColor); 
} 

編輯:這裏是一個展示jsFiddle我的第二個例子。

+0

它不工作知道爲什麼 – vini 2012-08-04 15:12:18

+1

我喜歡使用.prev()方法的第二個示例,因爲它避免了必須爲每個標籤分配id。節省大量工作,更重要的是提高可維護性。 – 2014-08-14 17:56:33

5
$('input[type="button"]').click(function(){ 
    changeColor('labelCity' , 'red'); 
}); 

function changeColor(id, newColor) { 

    $("#" + id).css("color", newColor); 

} 
1

下面是一個簡單的例子,使用jQuery將標籤文本的顏色更改爲紅色。

<script src="Scripts/jquery-1.9.0.min.js"></script> 
 
    <script> 
 

 
     $(document).ready(function() { 
 
      $('#btnChangeColor').click(function() { 
 
       $('#lbl1').css("color", "red"); 
 
      }) 
 
     }) 
 

 
     
 
    </script>
<body> 
 
    <form id="form1" runat="server"> 
 

 
     <label id="lbl1" >Hello friends save girl child</label> 
 
     <br /><br /><br /> 
 

 
     <input type="button" id="btnChangeColor" value="Change Color" /> 
 

 
    </form> 
 
</body>