简体   繁体   English

如何在JavaScript中触发事件的情况下检索对html对象的引用?

[英]How to retrieve the reference to an html object the fired an event in JavaScript?

I am pretty new in JavaScript and I have the following problem. 我在JavaScript中还很陌生,但遇到以下问题。 Into a JSP page I have something like this: 进入JSP页面,我会看到以下内容:

    <tbody>
        <c:forEach items="${listaProgetti.lista}" var="progetto" varStatus="itemProgetto">
            <tr id='<c:out value="${progetto.prgPro}" />'>
                <td><input type="checkbox" class="checkbox" onchange="changeCheckbox()"></td>
                .....................................................
                .....................................................
                .....................................................
            </tr>
        </c:forEach>
    </tbody>

So a you can see clicking on the checkbox it is call this changeCheckbox() that actually is something very simple: 因此,您可以看到单击复选框,将其称为changeChangebox()实际上非常简单:

function changeCheckbox() {
    alert("INTO changeCheckbox()");

    var checkedRowList = new Array();
}

The problem is that into this function I have to retrieve what is the input object that fire the change event (I think something like the this ) 问题在于,在该函数中,我必须检索引发更改事件的输入对象(我认为类似于this

How can I obtain the reference to the clicked checkbox in my previous changeCheckbox() function? 我如何在以前的changeCheckbox()函数中获取对单击复选框的引用?

The element is available in the event handler content attribute, not in changeCheckbox . 该元素在事件处理程序的content属性中可用,而在changeCheckbox不可用。 But you can pass it as an argument. 但是您可以将其作为参数传递。

  • Using this 使用this

     changeCheckbox(this) 

     function changeCheckbox(elem) { elem.style.marginLeft = '100px'; } 
     <input type="checkbox" onchange="changeCheckbox(this)" /> 

  • Using event : 使用event

     changeCheckbox(event.target) 

     function changeCheckbox(elem) { elem.style.marginLeft = '100px'; } 
     <input type="checkbox" onchange="changeCheckbox(event.target)" /> 

Note it would be better to use addEventListener : 请注意,最好使用addEventListener

document.querySelector('input').addEventListener('change', changeCheckbox);

Then the function changeCheckbox will receive the event object as its first parameter, and the current target element as the this value. 然后,功能changeCheckbox将接收事件对象作为其第一个参数,并接收当前目标元素作为this值。

 document.querySelector('input').addEventListener('change', changeCheckbox); function changeCheckbox(e) { e.target.style.marginLeft = '100px'; } 
 <input type="checkbox" /> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM