简体   繁体   中英

How to get data attribute of event target in svelte?

I'd like to get the value of data-url in:

  {#each profiles as p}
    <div data-url={p.url} class="item" on:click={goToPage}>
      <div class="row">
        <div class="col s12 l4">
          <div class="a">
             <br />
          </div>
        </div>
        <div class="col s12 l8">
          <p>
            <strong>{p.fn} {p.ln}</strong><br />
            {p.ttl}
          </p>
        </div>
      </div>
      {p.dsc}
       <hr />
    </div>
  {/each}

The function is:

  const goToPage = (e) => {
     var slug = e.target.querySelector("item").getAttribute("url");
    console.log("slug is:", slug);
    window.location.href = slug;
  };

However it does not work and I get

Uncaught TypeError: Cannot read properties of null (reading 'getAttribute')

I have tried other things like

e.target.querySelector("item").getAttribute("data-url");

and

e.target.getAttribute("data-url");

but none of them worked.

The simplest, most straightforward way is to simply pass the slug as an argument to the function instead:

<div data-url={p.url} class="item" on:click={() => goToPage(p.url)}>

and the function becomes:

const goToPage = (slug) => {
  console.log("slug is:", slug);
  window.location.href = slug;
};

e.target references the thing you just clicked, you'll need to use currentTarget instead and you don't need to do querySelector

EG:

var slug = e.currentTarget.getAttribute("data-url");

I've done a basic example

 function goToPage(e){ console.debug(e.currentTarget.getAttribute('data-url')); }
 <div data-url="https://google.com" class="item" onClick="goToPage(event)"> <div class="row"> <div class="col s12 l4"> <div class="a"> <br /> </div> </div> <div class="col s12 l8"> <p> <strong>{p.fn} {p.ln}</strong><br /> {p.ttl} </p> </div> </div> {p.dsc} <hr /> </div> <div data-url="https://google2.com" class="item" onClick="goToPage(event)"> <div class="row"> <div class="col s12 l4"> <div class="a"> <br /> </div> </div> <div class="col s12 l8"> <p> <strong>{p.fn} {p.ln}</strong><br /> {p.ttl} </p> </div> </div> {p.dsc} <hr /> </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