在jquery onlick中获取元素的id

getting the id of an element in jquery onlclick?

本文关键字:元素 id 获取 jquery onlick      更新时间:2023-12-19

这是一个非常简单的html页面示例

<span class ="title" id="title_1">this is</span> 
<span class="toggle" id="toggle_1>paragraph 1</span>
<span class ="title" id="title_2">this is</span> 
<span class="toggle" id="toggle_2">paragraph 2</span>

我试图用toggle函数做一个onlcik事件,所以基本上,当用户单击title 1时,toggle1会隐藏和显示,如果用户单击title 2,它会显示和隐藏toggle2,我希望这是有意义的。

 (document).ready(function() {
      $('.toggle').hide();
        $('#title_').click(function() {
        $('#toggle_').toggle('slow');
    });
      });

我是这样开始我的jquery的,只是不知道从这里该怎么办。感谢

您可以:

$('.toggle').hide();
$('.title').click(function() {
   $(this).next(".toggle").toggle('slow');
});

试试这个

(document).ready(function() {
      $('.toggle').hide();
      $('.title').click(function() {
                $(this).closest('.toggle').toggle('slow');
      });
});