我需要它被点击后,用JavaScript
问题描述:
我在JavaScript中的初学者,以移除元素的属性,我有这样的问题: HTML代码:我需要它被点击后,用JavaScript
<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属性。但仅限于点击的元素。 我不知道该怎么做。 你能帮忙吗?
答
在您的函数中尝试this.removeAttribute(cols) - 只要仅从您的文本区域调用init_area(),它就是指onclick事件附加到的元素。
答
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);
+0
谢谢大家的回答。对我来说,解决方案是Kris解决方案。 init_area =功能(事件){ event.target.removeAttribute(“cols”); } 我现在明白它是如何工作的,它在Chrome中工作。我没有在其他浏览器上测试它,但非常感谢你的回答 –
答
您需要使用此方法:的removeAttribute()
<textarea class="text_input" cols="40" rows="1" onclick="init_area();this.removeAttribute('cols'); "></textarea>
尖端:'this'在事件处理程序的功能是指一个事件已被attahed到的元素。 – Teemu
@Teemu:但只有当事件被绑定时*使用JavaScript。 'onclick'属性处理方式稍有不同。我认为他必须这样做:'onclick =“init_area(this);''。我没有永远使用'onclick'属性,因为它们是不好的做法。 –
我试过了: 函数init_area(){ \t this.removeAttribute(“cols”); } –