简体   繁体   English

将document.getElementById存储在变量中?

[英]Storing document.getElementById in a variable?

I have this script that is supposed to change the text of the button when the button is clicked. 我有这个脚本,应该在单击按钮时更改按钮的文本。

<body>
   <button onclick="toggleText(this);" id="id">Edit</button>
</body>

function toggleText(element){
    var text = document.getElementById(element.id).textContent;

    if (text == 'Edit') {
        text = 'Done';
    } else {
        text = 'Edit';
    }
}

But it doesn't work. 但这是行不通的。 It only works when you put document.getElementById(element.id).textContent directly into the if statements. 仅当您将document.getElementById(element.id).textContent直接放入if语句中时,它才起作用。

How do I get the variable to store properly? 如何获取变量以正确存储?

Since you already get the element, you don't need to get it again. 由于您已经获取了元素,因此无需再次获取它。 You can just use element. 您可以只使用元素。

But the reason why you can't change it is that you're only changing the variable that contains the text. 但是之所以不能更改,是因为您只更改了包含文本的变量。 It does not point to the element's properties. 它没有指向元素的属性。 You need to use this: 您需要使用此:

function toggleText(element){
  var text = element.textContent;

  if (text == 'Edit') {
    element.textContent = 'Done';
  } else {
    element.textContent = 'Edit';
  }
}

When you access document.getElementById(element.id).textContent you get the value of it, not the reference. 当您访问document.getElementById(element.id).textContent您将获得它的值,而不是引用。 So changes to it won't affect the element. 因此,对其进行更改不会影响该元素。

But when you assign element to variable, it gets reference to it. 但是,当您将元素分配给变量时,它将获得对它的引用。

var element = document.getElementById(element.id);
if (element.textContent == 'Edit') {
        element.textContent = 'Done';
    } else {
        element.textContent = 'Edit';
}

Just use: 只需使用:

index.js index.js

var mainText = document.getElementById("mainText").value;
document.write(mainText);

index.html index.html

<textarea id="mainText"></textarea>

As tymeJV commented, you can store by reference the element you get by id. 正如tymeJV所评论的那样,您可以通过引用存储通过id获得的元素。 Its property is stored by value. 它的属性按值存储。 Instead store the element in a variable and access its property from the variable. 而是将元素存储在变量中并从变量访问其属性。

var text = document.getElementById(element.id);

if (text.textContent == 'Edit') {
     text.textContent = 'Done';
} else {
    text.textContent = 'Edit';
}

Is jquery an option ? jquery是一个选择吗?

I used to do something like : 我曾经做过类似的事情:

var a = $('#theid');
A.something

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM