首页 > 解决方案 > 为什么 text() 和样式。宽度在 Js 中不起作用?

问题描述

我有一个如下所示的 HTML,

<div id ="b1>
     <i class="icon-clock"></i> <span class="font-weight-bold font-size-lg" id="currentTime"></span>
</div>

我无法current date and time特定的 Div中显示。

JS:

 // To display Date and time
    
    var target = document.getElementById('b1');
    var today = new Date();

    var date =
      today.getFullYear() +
      "-" +
      (today.getMonth() + 1) +
      "-" +
      today.getDate();

    var time =
      today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();

    var dateTime = date + " " + time;

   $(target).find('#currentTime').text(dateTime); // It dosen't displays the current date and time

我需要一个关于如何添加Width到进度条的解决方案,如下所示,

<div id = "b2">
    <div class="progress">
          <div class="progress-bar bg-success" id="div1" 
                style="width:0%">
           </div>
           <div class="progress-bar bg-warning" id="div2"
                style="width:0%">
           </div>
     </div>
</div>

如果我在 JS 中使用以下内容。

 var target = document.getElementById('b2');
 d1 = $(target).find('#div1');
 d2 = $(target).find('#div2');
 d1.style.width = 78 + "%";
 d2.style.width = 22 + "%";

我可以得到Uncaught TypeError: Cannot set properties of undefined (setting 'width')

无法获取进度条的宽度。如何将宽度添加到特定 div 内的进度条?

如何添加Current Date and time到特定的 Id ?

有人可以帮忙吗?

非常感谢。

标签: javascripthtmljquery

解决方案


发生这种情况是因为您假设 JQuery返回一个存在属性find()的 DOM 元素。style但实际上,它返回一个 jQuery 对象。

您可以使用.css()jQuery 方法进行更改。

d1.css( "width", "78%" );

推荐阅读