【问题标题】:jQuery invalid left-hand side errorjQuery无效的左侧错误
【发布时间】:2017-09-01 07:00:00
【问题描述】:

我收到此行的控制台错误:

$("#note" + noteCount).val() = note;

这是完整的功能:

function addNotes() {
    noteCount++;
    var note = $("#noteInput").val();
    console.log("Note: " + note);
    console.log("Note Count: " + noteCount);
    var display = document.createElement("div");
    document.getElementById("displayContainer").appendChild(display);
    display.className = "noteDisplay";
    display.id = "note" + noteCount;
    $("#note" + noteCount).val() = note;
}

如您所见,我正在创建一个 id 为 'note' + note count 的 div,但我不确定如何选择它来更改其值。

【问题讨论】:

标签: javascript jquery


【解决方案1】:

在创建DIV 时最好使用textContent 属性

 var display = document.createElement("div"); 
 display.id = "note" + noteCount;
 display.textContent = note;

或者,.text() as DIV 没有 value 属性,您需要将其作为参数提供给方法调用:

$("#note" + noteCount).text(note);

当您使用 jQuery 时,使用它创建 HTML

var display = $("<div>", {
    "text" : note,
    "id" : "note" + noteCount,
    "class" : "noteDisplay"     
});

display.appendTo('#displayContainer');

【讨论】:

  • 很好地发现它是一个div 元素。我会扩展答案以改进逻辑以摆脱 createElement/appendChild 丑陋。
【解决方案2】:

你的赋值方式是错误的。您需要将其作为参数传递给 val 函数,因为它是函数而不是属性

$("#note" + noteCount).val(note) ;

JQUERY DOCS

【讨论】:

  • 之前看文档时我很困惑,因为它说“此方法不接受任何参数”。不过谢谢你:)
  • 没问题:)。很高兴为您提供帮助
  • 我会在一秒钟内是的 :) 我确定你是对的,但是当我测试它时它没有显示出来。正在使用 id 和类名创建 div,但类也没有生效
【解决方案3】:

试一试

$("#note" + noteCount).val( note );

val 调用返回一个您不能用另一个值覆盖的值。

val = note; //has a different meaning, still not correct for your scenario

但是

val() = note; //not allowed 

由于 value 已经通过函数调用计算,因此左侧不是变量,而是一个值,您不能将值分配给一个值

【讨论】:

    【解决方案4】:

    使用jQuery时,应将值放在val()内;

    $("#note" + noteCount).val(note);
    

    【讨论】:

      猜你喜欢
      • 2013-10-01
      • 2017-04-26
      • 1970-01-01
      • 2020-08-02
      • 2017-12-30
      • 2019-09-18
      • 2020-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多