简体   繁体   English

如何使用jquery获取div的文本并设置元素的背景颜色

[英]How to get text of div and set in background color of element using jquery

$(".child").css("background-color", $(".child div").val());

<div class="flexbox" id="flexbox">
    <div class="child">
        <div>#69d2e7</div> 
    </div>
</div>

I am trying to get the value and make it background-color of that element but i don't know what's wrong我正在尝试获取该值并使其成为该元素的background-color ,但我不知道出了什么问题

The .val() method is primarily used to get the values of form elements such as input, select and textarea. .val()方法主要用于获取表单元素的值,例如 input、select 和 textarea。

You need to use .text() to getting text of div tag.您需要使用.text()来获取 div 标签的文本。

$(".child").css("background-color", $(".child div").text());

If you have multiple .child in your document you need to use bottom code如果您的文档中有多个.child ,则需要使用底部代码

 $(".child").each(function(){ $(this).css("background-color", $("div", this).text()); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="flexbox" id="flexbox"> <div class="child"> <div>#69d2e7</div> </div> <div class="child"> <div>red</div> </div> <div class="child"> <div>green</div> </div> </div>

Make sure that you are referencing the script file correctly and that it is truly in the root of your project.确保您正确引用了脚本文件,并且它确实位于项目的根目录中。 If not use relative paths to specify the location.如果不使用相对路径来指定位置。 Something like:类似的东西:

<script src="<%= Url.Content("~/scripts/jquery-1.3.2js") %>" type="text/javascript"></script>

Then it does not appear like you are actually calling the document ready function that prevents jquery from running before the document is loaded.然后它看起来不像您实际上是在调用防止 jquery 在加载文档之前运行的文档就绪函数。

$(document).ready(function(){ // jQuery methods go here... });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM