2015-09-04 41 views
0

我在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属性。但仅限于点击的元素。 我不知道该怎么做。 你能帮忙吗?

+0

尖端:'this'在事件处理程序的功能是指一个事件已被attahed到的元素。 – Teemu

+0

@Teemu:但只有当事件被绑定时*使用JavaScript。 'onclick'属性处理方式稍有不同。我认为他必须这样做:'onclick =“init_area(this);''。我没有永远使用'onclick'属性,因为它们是不好的做法。 –

+1

我试过了: 函数init_area(){ \t this.removeAttribute(“cols”); } –

回答

0

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

+0

阅读评论,似乎这是OP已经尝试过... – Teemu

+0

and the函数 函数init_area(){ \t this.removeAttribute(cols); } setTimeout(init_area,1000); 但是我在控制台中得到一个错误 Uncaught TypeError:this.removeAttribute不是一个函数 我迷路了 –

+0

你的函数没有使用'function init_area(el){el.removeAttribute(...) ;}' – Teemu

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

+0

谢谢大家的回答。对我来说,解决方案是Kris解决方案。 init_area =功能(事件){ event.target.removeAttribute(“cols”); } 我现在明白它是如何工作的,它在Chrome中工作。我没有在其他浏览器上测试它,但非常感谢你的回答 –

1

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

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