簡體   English   中英

如何使用jQuery更改新創建元素的屬性

[英]How to use jQuery to change attributes of a newly created element

我有以下代碼:

if (secsleft < 10) {
    var msg = 'No activity detected in the last 10 seconds.';
    if (auth == "true"){
        msg += '<br />You will be logged out in <br /><p id="counter">' + secsleft + '</p><br /> more seconds if no activity is detected.'; 
    } else {
        msg += '<br />You will be redirected in <br /><p id="counter">' + secsleft + '</p><br /> more seconds if no activity is detected.';
    }
    if (secsleft < 4) {
        //$("#counter").css({"color":"red"});
        //$("#counter").css("color", "red");
        document.getElementById("counter").style.color = "red";
    }
    Message('<span id="timer">' + msg + '</span>', 10000);
}

顯然,其目的是在少於四秒鍾時將計數器的顏色更改為紅色。 問題在於,首先在IF語句中創建帶有id =“ counter”的p標簽。 如果我想將事件綁定到該事件,那么我知道該怎么做。 就像這樣:

$(document).on(eventName, "#counter", function() {});

但這不適用於屬性。 從內部IF的注釋代碼中可以看到,我嘗試了各種組合,但是沒有任何效果。 順便說一句(令我驚訝的是),我可以輕松獲得該屬性,因此例如:

alert($("#counter").css("color"));

給我正確的價值。 那么,如何改變價值呢?

問題在於,直到該if語句之后,您才真正創建元素,因此所有的jQuery選擇器和getElementById調用都不會在頁面上找到任何內容,因為還沒有ID為“ counter”的東西。 您只需創建一個字符串,然后將其轉換為實際的元素。

您需要做的是創建一個實際元素,然后使用對其的引用,甚至可以在將其放入頁面之前更改其屬性。

var counter = document.createElement('p');
counter.id = 'counter';
counter.style.color = red;

或類似的規定。 我在這里向您展示了香草JS解決方案,但您可以使用jQuery進行相同的操作:

var counter = $('<p></p>');
counter.attr('id','counter');
counter.css('color','red');

您不能將document.getElementById()用於尚未添加到文檔中的元素。 這就是為什么它不起作用。

您可以簡化很多代碼。

  if (secsleft < 10) {
    var color = secsleft < 4 ? 'red' : 'inherit';
    var action = auth === 'true' ? 'logged out' : 'redirected';
    var msg = 'No activity detected in the last 10 seconds.'
            + '<br />You will be '+ action +' in '
            + '<span style="color: '+ color +'">' + secsleft + '</span>'
            + ' more seconds if no activity is detected.';  
    Message('<span id="timer">' + msg + '</span>', 10000);
  }

我看不到jQuery,但是您確實將它添加為標簽。 那么為什么不這樣做呢?

$("body").find("#counter").css("color", "red");

第一個問題是您尚未向document添加#counter元素,這意味着您無法使用document.getElementByID(...); 方法( 尚未 )。

為了能夠操作元素,您必須將其添加到文檔中,為此,您將使用:

// appends the new "div" element to the body (I.E: inserts the new element at the end of the body)
$("body").append("<div id='element-id'>Hello World!</div>");

您還可以使用以下方法:

// replaces the "innerHTML" of the "body" element with the new "div" element
$("body").html("<div id='element-id'>Hello World!</div>");
// prepends the new div to the body (I.E: inserts the element as the first child not the last child)
$("body").prepend("<div id='element-id'>Hello World!</div>");

現在,第二個問題是您正在獲取 CSS屬性的值,而不是對其進行 設置

要獲取CSS屬性的當前值,可以使用以下命令:

$("#element-id").css("property-name")

要在jQuery中更改 CSS屬性的值,可以使用以下命令:

// listen for an event to occur
$(document).on("event-name", function() {
  // change a single property of the element
  $("#element-id").css("property", "new-value");
});

您還可以使用如下JavaScript對象同時更改元素的多個屬性:

// listen for an event to occur
$(document).on("event-name", function() {
  // change multiple properties of the element using a JavaScript object
  $("#element-id").css({
    "property-name-one": "new-value",
    "property-name-two": "new-value"
  });
});

有關上述jQuery方法的更多信息,請訪問下面的鏈接:

希望這會有所幫助,祝你好運,並祝一切順利。

我認為有一種更整潔的方法可以實現您想要的,而可以使用jQuery添加樣式。 相反,最好是讓CSS處理樣式,讓jQuery在適當的地方添加類。

在下面的代碼中,<4檢查用於將值分配給counterClass變量,然后將其添加到您的counter元素。 然后,您可以添加css規則以實現紅色。

if (secsleft < 10) {
    var counterClass = "";
    if (secsleft < 4) {
        counterClass = "warning";
    }
    var msg = 'No activity detected in the last 10 seconds.';
    if (auth == "true") {
        msg += '<br />You will be logged out in <br />p id="counter" class="' + counterClass + '">' + secsleft + '</p><br /> more seconds if no activity is detected.';
    } else {
        msg += '<br />You will be redirected in <br /><p id="counter" class="' + counterClass + '">' + secsleft + '</p><br /> more seconds if no activity is detected.';
    }
    Message('<span id="timer">' + msg + '</span>', 10000);
}

希望這可以幫助。

您不會使用尚未添加到DOM中的getElementById來獲取元素。 您可以使用內聯樣式。

if (secsleft < 10) {
                var alertColor = "inherit";
                if(secsleft < 4) {
                    alertColor = "red";
                }
                var msg = 'No activity detected in the last 10 seconds.';
                if (auth == "true"){
                    msg += '<br />You will be logged out in <br /><p id="counter" style="' + alertColor + '">' + secsleft + '</p><br /> more seconds if no activity is detected.'; 
                } else {
                    msg += '<br />You will be redirected in <br /><p id="counter" style="' + alertColor + '">' + secsleft + '</p><br /> more seconds if no activity is detected.';
                }                    
                Message('<span id="timer">' + msg + '</span>', 10000);
            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM