2015-09-04 38 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> 
相關問題