2

I have 2 text area's that are generated automatically, and I need to use JavaScript to disable both when the page has loaded. The catch is because they are generated automatically I can't give them an ID because they would both have the ID - a big no.

Attempted Javascript:

document.getElementByClassName('option_window-size').disabled=true;

I know this works because if I change getElementbyClassName to ID then it will work if I give the text areas the ID as well. But as I say it needs to work off class. Also it can't work of the Name attribute because that is automatically generated per product and per page...

I have tried this but it just doesn't work and I can't figure out why not because it should as the only thing I have changed is from ID to CLASS

Text Areas

<textarea name="willbeautogenerated" class="option_window-size" cols="40" rows="5">willbeautogenerated</textarea>

Additional note: I have tried to count and assign them different IDs using PHP but it gets far to complex. Also it is only these two that need disabling, thus I can't just disable all text area's on the page.

4

8 回答 8

8

我知道这是可行的,因为如果我将 getElementByClassName 更改为 ID,那么如果我也为文本区域指定 ID,它也会起作用。但正如我所说,它需要在课外工作。

getElementsByClassName返回一个NodeList而不是Node本身。您必须遍历列表,或者如果您只期望1item,请选择 index 0

var nodes = document.getElementsByClassName("option_window-size"),
    i = 0, e;

while (e = nodes[i++]) e.disabled = true;
于 2013-07-16T13:48:03.633 回答
2

jQuery 让这变得非常简单:

$(".selector").prop("disabled", true);

虽然!应该注意的是,此注释出现在 和 的手册页$.prop()$.attr()

注意:尝试更改通过 HTML 创建或已在 HTML 文档中的输入元素的 type 属性(或属性)将导致 Internet Explorer 6、7 或 8 引发错误。

这并不直接适用于您的问题,但您正在更改输入元素上的prop/ s,因此请注意。attr

但是使用普通的旧 JS 仍然是可能的:

var els = document.getElementsByClassName("selector"); // note: Elements, not Element

for(var e = 0; e < els.length; e++)
{
    els[e].disabled = true;
}

getElementsByClassName 返回一个 NodeList,您只需遍历其中的每个元素。

于 2013-07-16T13:52:38.410 回答
1

使用 Jquery,您可以:

//make sure to use .prop() and not .attr() when setting properties of an element
$('.option_window').prop('disabled', true);
于 2013-07-16T13:50:30.830 回答
1

您可以使用类选择器,

$('.option_window').attr('disabled', true);

或者

$('.option_window')[0].disabled = true;
于 2013-07-16T13:48:19.620 回答
0

对于第一个元素,您在元素中的缺失和元素类似于 [0] 的索引。

  document.getElementsByClassName('option_window-size')[0].disabled=true;

或者

  document.getElementsByName('willbeautogenerated')[0].disabled=true;
于 2013-07-16T13:55:18.457 回答
0

在 jquery 中使用.prop()方法禁用 texarea ...

      $('.option_window-size').prop('disabled', true);
于 2013-07-16T13:57:02.853 回答
0

使用 jQuery 禁用文本区域:

$('.option_window-size').attr('disabled', true);
于 2013-07-16T13:49:17.070 回答
0

您可以使用 CSS:

.option_window-size{display:none;}
于 2013-07-16T14:24:15.037 回答