繁体   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