简体   繁体   中英

“Hiding” javascript events in DOM

I'm developing a custom ordering process and I'm using AJAX requests and dynamic forms a lot to complete parts of the ordering process, but I'd like to cleanup the way I'm doing it into terms of the HTML. I'm using jQuery too.

In looking at applications like Google's word processor, I can see that both the DOM and source exhibit no javascript event attributes. For example:

<div id="docs-file-menu" role="menuitem" class="menu-button goog-control goog-inline-block" aria-disabled="false" aria-expanded="false" aria-haspopup="true" style="-webkit-user-select: none;">File</div>

My guess is that a script is registering Javascript events after the fact based on the HTML attributes.

My website is much less complex, but I was wondering how to approach this as I currently have button styled <a><img></a> tags (or similar) that call Javascript functions, which works fine, but seems like the lesser (and old school) approach. For example:

<a href="javascript:Customisation.beginNewPair()">
    <img src="images/begin-new.gif" />
</a>

Here is a simple example on how to use data attributes and an eventListener on click:

var a = document.getElementById('docs-file-menu');
a.addEventListener('click', test);

function test () {
var dis = a.getAttribute('aria-disabled');
var exp = a.getAttribute('aria-expanded');
var has = a.getAttribute('aria-haspopup');


    if (dis == 'true') {
        alert('disabled = true');
    }
     if (exp == 'true') {
        alert('expanded = true');
    }
    if (has == 'true') {
        alert('haspopup = true');
    }

}

You also could access the different data attributes on page load and, according to them, you could be running different functions.

Here's a simple DEMO with onclick event, simply click on File

What you want is addEventListener .

How you access the elements is another question, but say you want an alert every time somebody clicks on a box.

 var box = document.getElementById('box'); box.addEventListener('click', function(){ alert(); }); 
 <div id="box" style="width:150px;height:150px;background:blue;"></div> 

You can also put what happens in a real function:

 function doSomething(){ alert(); } var box = document.getElementById('box'); box.addEventListener('click', doSomething); 
 <div id="box" style="width:150px;height:150px;background:blue;"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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