javascript - 当我单击元素数学/物理/化学时如何使用 jquery 获取跨度 ID

标签 javascript jquery html css

<!DOCTYPE html>
<html>

<head>
    <title>jQuery Accordion Menu Demo</title>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script src="main.js" type="text/javascript"></script>
</head>

<body>
    <div id='menu'>
        <ul>
            <li> <a href='#'><span id="Science">Science</span></a>
                <ul>
                    <li><a href='#'>Mathematics</a></li>
                    <li><a href='#'>Physics</a></li>
                    <li><a href='#'>Chemistry</a></li>
                </ul>
            </li>
        </ul>
    </div>
    <script>
        $('#menu li>ul>li').click(function() {
            alert(span id is Science);
        });
    </script>
</body>

</html>

这是我正在尝试做的代码。

我希望当用户点击数学、物理或化学时,它应该使用 JQuery 在 ALERT 中显示 parent 的 SPAN ID。

最佳答案

你可以使用关系

$('#menu li>ul>li').click(function() {
    var id = $(this)
        .parent() //Travese up to UL
        .closest('li') //Travese up to li
        .find('span') //Finds the span
        .attr('id'); //Fetches the id attribute

    alert('span id is: ' + id);
});

$(function() {
  $('#menu li>ul>li').click(function() {
    var id = $(this)
      .parent() //Travese up to UL
      .closest('li') //Travese up to li
      .find('span') //Finds the span
      .attr('id'); //Fetches the id attribute

    alert('span id is: ' + id);
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='menu'>
  <ul>
    <li> <a href='#'><span id="Science">Science</span></a>
      <ul>
        <li><a href='#'>Mathematics</a>
        </li>
        <li><a href='#'>Physics</a>
        </li>
        <li><a href='#'>Chemistry</a>
        </li>
      </ul>
    </li>
  </ul>
</div>

关于javascript - 当我单击元素数学/物理/化学时如何使用 jquery 获取跨度 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34986970/

相关文章:

jquery - 在 ColdFusion 中显示和/或使用无效的表单字段,如果您只是尝试用井号包裹它们

javascript - 类型错误 : n is undefined in underscore. min.js

php - 当java脚本警报消息弹出时隐藏html控件

javascript - Node.js Object 对象没有方法 'hasOwnProperty'

javascript - 用于多个 '+' 标志的电子邮件地址验证 javascript

javascript - Gulp browser-sync 在哪里放置文件夹?

javascript - Meteor:点击按钮时显示一些内容

javascript - 关于禁用按钮解决方法的 Bootstrap 工具提示

html - 图像和 h2 不会水平对齐

javascript - 如何在 package.json 的项目目录中为 gulp 文件创建路径