jquery - 使用 jquery 更改标签的颜色?

标签 jquery html submit label

我想在点击按钮时将标签的颜色更改为红色

然而代码并不能正常工作,一切似乎都是正确的

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

请帮忙

最佳答案

您将“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演示我的第二个示例。

关于jquery - 使用 jquery 更改标签的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11809378/

相关文章:

javascript - 自动刷新使用 JSON 加载的内容

javascript - 如何在按下按钮时更新变量?

html - Offshape Arrow - 响应?

javascript - 表单提交时弹出

javascript - Angular ng-submit 只允许作用域内的函数

javascript - WordPress 插件中的 jQuery

javascript - jQuery onClick 行将行移动到另一个表

javascript - jQuery - 当 session 过期或销毁时立即重定向

css - 我可以使用表格作为背景并在其上添加不同的表格吗?

javascript - 为什么在定义对象时不能在 (JavaScript) Worker 中使用它?