选择< div>使用jQuery [英] selecting <div> using jQuery

查看:61
本文介绍了选择< div>使用jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一天前问了一个大问题,但没有得到足够好的答案,所以我将问题分成几部分。这是一部分:

I asked here a big question 1 day ago, but didn't get enough good answers, so I divided the question into parts. This is one part:

看看这段代码:

<?php
    foreach($tickets as $key=>$value)
           {
?>
               <div id="topic_<?php echo $key;?>"  data-id="<?php echo $key;?>" onclick="showDetails()">
                   ------------------------------
               </div>
               <div id="details_<?php echo $key;?>"  data-id="<?php echo $key;?>">
                   ------------------------------
               </div>
<?php
           }
?>

在这里,我们有一些< div> s(topic _...和details _...),每个都有唯一的id( data-id )。我们不知道这些< div> 中会有多少,因为 foreach()环。所有详细信息< div> s将在第一时间隐藏。现在,我想要的是,当我点击主题< div> 时,其相应的详细信息< div> 。我想我应该使用一个函数并在 onclick 事件中调用该函数,这就是为什么我使用 onclick =showDetails()在主题< div> 中。如果我错了或者您有更好的想法,请与我分享。以下是Javascript代码:

Here, we have some <div>s ("topic_..." and "details_..."), each with unique id(data-id). We don't know how much of these <div>s will be there, because of the foreach() loop. All "details" <div>s will be hidden at the first time. Now, what I want, when I click on a "topic" <div>, its corresponding "details" <div> will be shown. I think I should use a function and call that function in the onclick event, that's why I used onclick="showDetails()" in the "topic" <div>. If I am wrong or you have a better idea, please share with me. Here is the Javascript code:

<script>
    $(document).ready(function(){
           $("#details_").hide();
    });
    function showDetails()
    {
        var id=$(this).attr('data-id');
        $("#details_"+id).show();
    }
</script>

我知道我无法检测到所有详情_......< div> 此处,可能在 showDetails()函数中也存在一些问题。请帮帮我。

I know I couldn't detect all "details_......" <div>s here, and may be there are also some problems in the showDetails() function. Please help me.

谢谢大家。

推荐答案

你可以避免所有这些ID废话都是通过使用相对选择器。

You can avoid all of this ID nonsense by using relative selectors.

showDetails(this)< ---发送参考到当前元素

showDetails(this) <--- send a refernce to the current element

function showDetails(element) {
      $(element).next('div').show().
}

这篇关于选择&lt; div&gt;使用jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆