我想使用querySelector(),但我发现Svelte有另一种方法可以做到这一点.

通过使用bind:this


问题是,有时它会起作用,但大多数时候它永远不会起作用

通过输出undefined

下面是一个简单的例子:

<script>
  let thisDiv;

  console.log(thisDiv) // ❌ "undefined" ✅ "<div>"
</script>

<div bind:this={thisDiv}>hello world</div>

真正的虫子

但真正的问题在这里

因为我现在不需要console.log

我之前写的东西只是为了让你理解这个错误
这样我就可以开始输入更多信息.

因为我有一个function,它使用这个变量
并在事件"on:animationend"开始时调用该函数.

如下所示:

<div
  bind:this={thisDiv}
  on:animationend={doStuff()}
></div>

问题是animationend仍然是控制台.记录thisDiv undefined

也许是速度的问题?

好的,好的,好的.

但css中的动画只有50毫秒长.也try 了0.5s

而且,css不会阻止该脚本,所以当css制作他的动画时,js将继续工作(据我所知)

而0.5s我认为对于简单的bind:this(QuerySelector)来说太多了

how is it even possible?半秒,获取一个普通的querySelector,但仍然什么都没有.

enter image description here


源代码

下面是REPL Online Svelte源代码示例:

https://svelte.dev/repl/b49d019ce7f8426b80295158b091520f?version=3.50.1

确保取消注释Child.svelte中的第9行

.或者直接看到这个

App.svelte

<script>
    import Child from "./Child.svelte"
    
    function generateExample() {
        let output = [];
        
        for(let i=0; i<=100; i++) {
            output = [
                ...output, `text ${i}`
            ]
        }
        
        return output;
    }
    
  let array = generateExample()
</script>

{#each array as item, index}
   <Child {index}>
      {item}
   </Child>
{/each}

Child.svelte

<script>
  export let index;
  const DELAY = 50;
  
  let thisDiv;

    // UNCOMMENT THE NEXT LINE
  function doStuff() {
         // thisDiv.scrollIntoView(); 
  }
</script>

<div
  style="--delay:{index * DELAY}ms;"
  bind:this={thisDiv}
  on:animationend={doStuff()}
  >
  <slot></slot>
</div>

<style>
  div {
    animation: show var(--delay);
  }

  @keyframes show {
    from {
      translate: 100vw;
    }
    to {
      translate: 0;
    }
  }
</style>

推荐答案

实际上,您的代码只是有问题,您调用了处理程序,而不是引用它:

on:animationend={doStuff()}

应该是:

on:animationend={doStuff}

REPL

此外,您不需要bind:this,可以使用Event对象:

function doStuff(e) {
    e.target.scrollIntoView();
}

REPL

Javascript相关问答推荐

如何才能拥有在jQuery终端中执行命令的链接?

react—router v6:路由没有路径

为什么这个JS模块在TypeScript中使用默认属性导入?""

从Node JS将对象数组中的数据插入Postgres表

用于编辑CSS样式的Java脚本

编辑文本无响应.onClick(扩展脚本)

TypeError:无法分解';React2.useContext(...)';的属性';basename';,因为它为空

Web Crypto API解密失败,RSA-OAEP

使用Nuxt Apollo在Piniastore 中获取产品细节

为什么这个.add.group({})在教程中运行得很好,但在我的游戏中就不行了?

当我try 将值更改为True时,按钮不会锁定

P5.js中的分形树

有没有办法更改Chart.js 3.x.x中主要刻度的字体?

使用API调用的VUE 3键盘输入同步问题

连续添加promise 时,如何在所有promise 都已结算时解除加载覆盖

$GTE的mongoose 问题

无法在Adyen自定义卡安全字段创建中使用自定义占位符

浮动标签效果移除时,所需的也被移除

Reaction:从子组件调用父组件中的函数

如何将.jsx转换为.tsx