【问题标题】:Not Able to change css using JS无法使用 JS 更改 css
【发布时间】:2021-11-08 10:46:53
【问题描述】:

我正在研究还涉及 JavaScript 的 DJango,我需要在执行某个操作后更改元素的背景颜色,但我无法这样做。 以下代码是项目中使用的唯一 Javascript 文件。

function create_email(email){
const element = document.createElement('div');
element.id = "email";
element.innerHTML= `<b>${email.sender}</b>: ${email.subject}<p id='right' ><button id ="view" 
onclick="view_mail(${email.id})"class="btn btn-primary">View</button>${email.timestamp}<button 
id="archive" onclick="archive(${email.id})" class="btn btn-secondary">Archive</button><p>`;
element.addEventListener('click', function() {
console.log(`This message is sent by ${email.sender}`)
});
document.querySelector('#emails-view').append(element);
}

上面我使用 Javascript 创建了一个 Element div 并分配了 id email ,稍后我将更改这个元素的 css 属性:-

function read(id){
fetch(`/emails/${id}`, {
method: 'PUT',
body: JSON.stringify({
    read: true
})
})
document.getElementById("email").style.backgroundColor="red";
}

在这个函数中,我尝试改变元素的背景颜色,但没有改变任何东西。 请注意,此函数正在运行,因为我尝试仅更改此函数中的其他元素属性并且它们有效。 元素 email div 位于 ID 为 emails-view 的 div 中。而且我可以更改电子邮件视图 div 的背景,但不能更改此 div 块内的电子邮件 div。

【问题讨论】:

    标签: javascript html css django web-development-server


    【解决方案1】:

    如果需要更改view_mail函数中的css:

    const email = {
      id: 1,
      sender: 'John',
      subject: 'Message',
      timestamp: '13/09/2021'
    }
    function create_email(email){
      const element = document.createElement('div');
      element.id = "email";
      element.innerHTML = `<b>${email.sender}</b>: ${email.subject}
      <p id='right'>
      <button id ="view" onclick="view_mail(${email.id})"class="btn btn-primary">View</button>${email.timestamp}
      <button id="archive" onclick="archive(${email.id})" class="btn btn-secondary">Archive</button>
      <p>`;
      element.addEventListener('click', function() {
        console.log(`This message is sent by ${email.sender}`)
      });
      document.querySelector('#emails-view').append(element);
    }
    function view_mail(id) {
      document.getElementById("email").style.backgroundColor="red";
    }
    
    create_email(email)
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
    
    <div id="emails-view"></div>

    【讨论】:

    • 为什么我不能使用我的代码进行更改?正在调用读取函数,但无法更改 css。
    • 对不起伙计,我没听懂你的意思,你能澄清你的问题吗?
    • 我做了和你一样的事情。但它在我的项目中不起作用 css 属性没有被更改为什么?
    猜你喜欢
    • 2018-12-12
    • 1970-01-01
    • 2020-10-11
    • 2014-02-20
    • 2022-11-01
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多