【问题标题】:Are there any way to do following using Jquery Function有什么方法可以使用 Jquery 函数进行以下操作
【发布时间】:2021-07-31 05:00:49
【问题描述】:

在我的 HTML 网站上; 当用户点击#seasons > div:nth-child(1) > div.se-a > ul > li:nth-child(1)这个元素我需要运行函数myFunc(S1E1x,S1E1y,S1E1z);

所以当用户点击#seasons > div:nth-child(1) > div.se-a > ul > li:nth-child(2)这个元素我需要运行函数myFunc(S1E2x,S1E2y,S1E2z);

当用户点击#seasons > div:nth-child(5) > div.se-a > ul > li:nth-child(10)这个元素我需要运行函数myFunc(S5E10x,S5E10y,S5E10z);

作为通用术语,当有人点击#seasons > div:nth-child(p) > div.se-a > ul > li:nth-child(q)这个元素我需要运行函数myFunc(SpEqx,SpEqy,SpEqz);

有没有什么捷径可以做到这一点。目前我手动将onclick="myFunc(SpEqx,SpEqy,SpEqz)" 添加到所有#seasons > div:nth-child(p) > div.se-a > ul > li:nth-child(q)

请帮帮我!!!

【问题讨论】:

  • 请将您的源代码添加到此问题中,以便我们为您提供帮助。
  • 你需要使用 index... jQuery("#seasons > div:nth-child(p) > div.se-a > ul > li:nth-child(q)"). index() 将返回元素的索引,它将是一个整数,从第一个元素的 0 开始。所以给那个索引加1,你会得到第n个元素索引
  • 这些元素是如何生成的?知道它们是如何创建的,有很多方法可以简化这一点

标签: javascript html jquery node.js arrays


【解决方案1】:

看起来唯一的变化取决于其容器中 <li> 子元素的索引,因此将其设为 DRY 并不难 - 但您还有另一个问题,您使用的是大量独立变量而不是更合理的数据结构,使得动态访问变得困难。请改用数组。例如,而不是像

这样的函数调用
myFunc(S5E10x,S5E10y,S5E10z)

改为使用单个对象数组:

// corresponds to season 5, episode 10: remember, arrays are 0-indexed
const { x, y, z } = SE[4][9];
myFunc(x, y, z);

所以大 SE 数组看起来像

[
  // S1
  [
    // E1
    {
      x: <value of S1E1x>,
      y: <value of S1E1y>,
      z: <value of S1E1z>,
    },
    // E2
    // etc

然后,使用事件委托来监视点击。在点击时,在父&lt;ul&gt;中识别被点击的&lt;li&gt;的索引以找到剧集索引,在父#seasons中识别被点击的季节的索引以找到季节索引。然后在 SE 数组中查找匹配项:

const seasons = document.querySelector('#seasons');
seasons.addEventListener('click', (e) => {
  const { target } = e;

  // only process clicks on an episode `<li>`:
  if (!target.matches('li')) return;

  const seasonParent = target.closest('#seasons > div');
  const seasonIndex = [...seasonParent.children].indexOf(seasonParent);

  const episodeParent = target.parentElement;
  const episodeIndex = [...episodeParent.children].indexOf(target);

  const { x, y, z } = SE[seasonIndex][episodeIndex];
  myFunc(x, y, z);
});

【讨论】:

    猜你喜欢
    • 2015-07-02
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    相关资源
    最近更新 更多