对象不支持属性或方法“文本”

Object doesn't support property or method 'text'

本文关键字:文本 方法 不支持 属性 对象      更新时间:2023-09-26

当我调用setDefaultLocalPrinter()时,标题中出现错误。如果我像这样称 span b y 它的 ID $("#spanId").text("test")那么它可以工作,但它不像下面那样工作

<span id="defaultLocalPrinterName<c:out value="${entry.index}"/>">Printer</span>
function setDefaultLocalPrinter(printerName) {
        console.log("setDefaultLocalPrinter: " + printerName)
        $('span[id^="defaultLocalPrinterName"]').each(function(){
            this.text(printerName)
        });
    }

each() 中使用 $(this)

$(this).text(printerName);

this是普通的JavaScript对象。它不能用于调用在jQuery原型上定义的方法。 $(this) this包装在jQuery中,可以访问jQuery原型上定义的所有方法和属性。

如果你想使用纯JavaScript,

this.textContent = printerName;

each甚至不需要,textContent可以直接使用选择器上的text()进行设置。

$('span[id^="defaultLocalPrinterName"]').text(printerName);
相关文章: