简体   繁体   中英

How could I add the ability to navigate onclick to the code?

I am trying to add links eg <a> to the code from here , it is a treeview using JS and JSON.

It fully works and the children are already <a></a> with href="#", I have replaced the following code, to grab a href: "example.com" attribute from the JSON and set it to the href, which works. I have also made a change to the onclick, but that only does something if you click twice:/

I would like for it to instantly href, and not when you click twice on the child.

class SimpleTree extends Emitter {
    constructor(parent, properties = {}) {
      super();
      // do not toggle with click
      parent.addEventListener('click', e => {
        // e.clientX to prevent stopping Enter key
        // e.detail to prevent dbl-click
        // e.offsetX to allow plus and minus clicking
        if (e && e.clientX && e.detail === 1 && e.offsetX >= 0) {
            if (parent.href != null) {
                window.location.href = parent.href;
            }
          return e.preventDefault();
        }
        const active = this.active();
        if (active && active.dataset.type === SimpleTree.FILE) {
          e.preventDefault();
          this.emit('action', active);
          if (properties['no-focus-on-action'] === true) {
            window.clearTimeout(this.id);
          }
        }
      });
[...]
class SelectTree extends AsyncTree {
    constructor(parent, options = {}) {
      super(parent, options);
      /* multiple clicks outside of elements */
      parent.addEventListener('click', e => {
        if (e.target.href !== '#' || e.target.href !== 'javascript:void(0)' || e.target.href !== undefined || e.target.href !== '' || e.target.href !== null) {
            window.open(href, '_blank');
        }
        if (e.detail > 1) {
          const active = this.active();
          if (active && active !== e.target) {
            if (e.target.tagName === 'A' || e.target.tagName === 'SUMMARY') {
              return this.select(e.target, 'click');
            }
          }
          if (active) {
            this.focus(active);
          }
        }
      });

The simplest answer to this, add an eventlistener for the <a> element and navigate if it's not empty, null, etc.

Solution below is using Jquery.

$("a").click(function(e) {
  e.preventDefault();
  var href = $(this).attr("href");
  if (href !== '#' || href !== 'javascript:void(0)' || href !== undefined || href !== '' || href !== null) {
    window.open(href, '_blank');
  }
});

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