JQuery使用按钮更改背景颜色

时间:2017-01-17 11:20:00

标签: javascript jquery html

目前我有2个按钮,其中一个应该将背景颜色更改为黄色,另一个应该更改为红色,但是由于某种原因它似乎不起作用,控制台中没有错误但仍然没有结果:

HTML:

    <button class="btn btn-default form-control margin" value="yellow" class="color">Background</button>
    <button class="btn btn-default form-control margin" value="red" class="color">Background</button>

JS:

$(document).ready ( function(){
        $('.color').click(function(){
        $('#content-link2 > #content').css({"background-color": ($(this).attr("value"))
        });
   });
});

HTML的其余部分:

<div id="content-link2"></div>

在该div内部注入了另一个html页面:

<!DOCTYPE html>

<html>
<head>
    <title>Template 1</title>
        <link href="http://localhost/fyproject/public/templates/css.css" rel="stylesheet" type="text/css">
</head>
<body>
    <div class="logo">
        <img class="images" id="image" src="#" alt="Your Logo"/>
    </div>
<div  contenteditable="true" id="content" class="draggable ui-widget-content refresh"><p>hlo</p></div>
<div id="comments">
<form name="forma">
<textarea name="commentUser" id="commentUser" class="refresh" cols="40" rows="5">
Comments here...
</textarea><br>
<input type="submit" value="Ready!" id="send-data" /><!--onClick="writeComment(e);"--> 
<div id ="editTxt" class="refresh" contenteditable="true">
<p>This text can be by the user.</p>
</div>
</div>
</form>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

试试这个:(每个标签只添加一个类属性)

<button class="btn btn-default form-control margin color" value="yellow">Background</button>
<button class="btn btn-default form-control margin color" value="red">Background</button>

然后:

$(document).ready ( function(){
    $('.color').click(function(){
    $('#content').css("background-color",$(this).attr("value"))
    });
  });