我需要在使用JavaScript单击后从元素中删除属性

时间:2015-09-04 15:08:02

标签: javascript html

我是JavaScript的初学者,我有这个问题: HTML代码:

<textarea class="text_input" cols="40" rows="1" onclick="init_area();"></textarea>
<textarea class="text_input" cols="40" rows="1" onclick="init_area();"></textarea>

我希望当用户点击此textarea元素以删除cols属性时,例如。但仅适用于单击的元素。 我不知道该怎么做。 你能帮忙吗?

3 个答案:

答案 0 :(得分:1)

您需要使用此方法: removeAttribute()

<textarea class="text_input" cols="40" rows="1" onclick="init_area();this.removeAttribute('cols'); "></textarea>

答案 1 :(得分:0)

在你的函数中尝试this.removeAttribute(cols) - 这指的是onclick事件附加到的元素,只要init_area()只从你的文本区域调用。

答案 2 :(得分:0)

HTML:

<textarea class="text_input" cols="40" rows="1" onclick="init_area(event);"></textarea>
<textarea class="text_input" cols="40" rows="1" onclick="init_area(event);"></textarea>

在你的JS文件中:

init_area = function(event) {
  event.target.removeAttribute("cols");
}

但是你应该尝试从HTML元素中删除函数调用并将其移动到JS文件中:

yourElement.addEventListener(eventName, eventHandler);

https://developer.mozilla.org/en-US/docs/Web/Events/click

相关问题