更改 JQuery 中段落的颜色

Changing the color of a paragraph in JQuery

所以我在一个段落中有一个按钮。当用户按下按钮时,我希望它更改它所在的特定段落的背景颜色。这是我目前拥有的 JQuery:

$('<button/>',
    {
        text: "Done",
        click: function () {
            $("p:first").addClass("first");
            $(".first").css({ 'background-color': 'green' });
        }
    });

我的想法是先把段落放到一个特定的class中,然后给它一个背景色。但是我的按钮不起作用,当我检查控制台时,我没有收到任何错误。还有什么我可以尝试的吗?

问题中的当前 button jQuery 对象没有 p 子元素。

尝试用 html: 代替 text: ;在 <p></p> 中包装 "Done" 字符串;在 click 事件中的选择器处使用 context 来引用 this button 元素;使用 .appendTo() 将 jQuery 对象 button 附加到文档

$("<button/>", {
  html: "<p>Done</p>",
  click: function() {
    $("p:first", this).addClass("first");
  }
}).appendTo("body")
.first {
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

您可以像下面这样操作。使用 closest 函数查找父级 pcss 函数更改背景颜色。

$("button").click(function () {
     $(this).closest('p').css('background-color', 'red');
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
    <button>Click</button>
</p>

你可以做到这一点

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<style>
.myclass
{
  background-color: yellow;
}
.newclass
{
  background-color: red;
}
</style>
</head>

<body>
<p class="myclass">This is a paragraph.
<button id="changecolor"> change color </button>
</p>
<script>
$('#changecolor').click(function()
{
$(this).parent().removeClass('myclass').addClass('newclass');
}

);
</script>
</body>
</html>

When the user pushes the button, I want it to change the background color of the specific paragraph it is in.

下面的代码可以完成工作!

$('p button').click(function(){
  $(this).parent('p').css('backgroundColor', 'yellow');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
  <button>Click Me</button>
  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
</p>

<p>
  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
  <button>Click Me</button>
  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
</p>

<p>
  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
  <button>Click Me</button>
  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
</p>