簡體   English   中英

在創建的元素Pure JS中定位元素

[英]Targeting an element within a created element, Pure JS

我一直在開發一小段代碼,現在主要使用Pure JS,雖然我不精通JS,但是我可以在合理范圍內解決它。 我正在嘗試定位放置在JS創建的div中的HTML元素。

這個想法是當字符計數器的顏色變為50時最終變為0,然后最終變為0。我試圖自己實現以下代碼段,但在使它正確工作方面遇到困難。

經過一番摸索之后,我偶然發現了一個位於此處的問題Stack Overflow Question 提到需要更深入地尋找目標對象,即var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0]; 但是我覺得這並不真正適用於我,因為我沒有給創建的div一個ID或使用類。

這是我嘗試實現的

 // create wrapper element
  this.wrapper = document.createElement("div");
  this.wrapper.innerHTML = 'Chars left: <span id="int">' + (this.MAX - input.value.length), '</span>';

// The <span></span> element is the one I am trying to adjust.

// check counter value
var tail = document.getElementById("int");

if (this.MAX - this.INPUT.value.length <= 50) {
    tail.style.color = "#ffa";
} else if (this.MAX - this.INPUT.value.length <= 0) {
    tail.style.color = "#f00";
}

您可以找到我使用JSFiddle創建的完整代碼段。 誰能幫助我確定我在這里所缺少的東西,或者啟發我有關我是否正在解決這一錯誤?

看起來您需要在將字符輸入到輸入中時進行偵聽。 這些.value.length屬性不會實時更新,因此您需要在用戶每次按鍵時進行檢查。

// create wrapper element
this.wrapper = document.createElement("div");
this.wrapper.innerHTML = 'Chars left: <span id="int">' + (this.MAX - input.value.length), '</span>';

// check counter value
var tail = document.getElementById("int");

// Inside the event handler function, the "this" keyword changes meaning to mean the element on which the event listener is attached. Redefining the variable here is one way to get max inside the handler.
var max = this.MAX;

this.INPUT.addEventListener('keyup', function () {
    if (max - this.value.length <= 50) {
        tail.style.color = "#ffa";
    } else if (max - this.value.length <= 0) {
        tail.style.color = "#f00";
    }
}

您可能還想檢查else if (max - this.value.length <= 0)的邏輯, else if (max - this.value.length <= 0) -長度永遠不會小於零:)另外,當長度超過50時,您想發生什么?

在此樣式化:

TextAreaRanger.prototype["update"] = function() {.....}

暫無
暫無

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

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