我对使用 toggle(( 隐藏链接的 js 有问题。问题是:
我得到一个企业列表,每个企业都有一个隐藏在href链接上的电话号码。单击一个链接时,仅显示单击的链接数,显示所有链接的所有数量我的JS代码:
$(document).ready(function(){
$("p").css('display', 'none')
$("a").click( function(){
$("p").slideToggle('slow');
});
});
我知道为什么,但我不知道如何通过 id 显示。 我使用 php。
<div id='phone'><a href='#' id='$eid'>Veja nosso telefone!
<p".$e2['telefone']."/>
$eid
我从DB得到的。
这是一种可能的方法。您可以使用$(this)
选择器告诉解释器您需要当前元素。
$(document).ready(function(){
$("p").css('display', 'none')
$("a").click( function(){
$(this).slideToggle('slow'); // would only slidetoggle $(this) which is the element that was just clicked.
});
});
<div id='phone'><a href='#' id='$eid'>Veja nosso telefone!
<p".$e2['telefone']."/>
我ASUME你的HTML应该看起来像这样:
<div id='phone'>
<a href='#' id='someID01'>Veja nosso telefone!
<p>012-45567890</p>
</a>
<a href='#' id='someID02'>Veja nosso telefone!
<p>5486</p>
</a>
<a href='#' id='someID03'>Veja nosso telefone!
<p>088-9001</p>
</a>
<a href='#' id='someID04'>Veja nosso telefone!
<p>Secret!</p>
</a>
<!-- etc. -->
</div>
那么这个JavaScript就可以工作
了$(function () {
$('#phone > a').click(function (e) {
// Do not follow the link, even if it's '#'
e.preventDefault();
// Toggle it's p-element
$(this).find('p').slideToggle('slow');
});
});
当您单击链接时,此脚本将切换链接内的p
元素。
尝试:
$("a").click( function(){
$(this).find("p").slideToggle('slow');
});
this
函数内部click
是指单击DOM元素,find
会让您在其中p
元素。
使用 .
引用类,#
引用 ID。非前缀名称引用标签类型(即 p
、div
、span
等(。对于css和jQuery都是如此。
$('.class') // references all instances of class named 'class'.
$('#id') // references item with id = 'id'.
有关更多详细信息,请参阅官方 jQuery 选择器指南。
好吧,让我们从这样一个事实开始,即你不需要放置你的javascript来为元素设置默认样式。
首先,不要在你的javascript中这样做:
$("p").css('display', 'none');
您应该使用 CSS 来设置默认样式:
p{display:none}
没有不必要的javascript代码可以为用户带来更好的性能。
其次,我不确定 #phone 是否是 ID 的正确语义用法,ID 的用法适用于在您的标记上是唯一的东西。因此,对于将在列表中使用的内容,语义选择是类。
所以,让我们解决你的代码问题...
首先,你的标记也有一些问题,你的p标签不正确,你是一个标签没有关闭。下面是对 HTML 代码的可能更正:
<div class='phone'>
<a href='#' id='<?= $eid; ?>'>Veja nosso telefone!</a>
<p><?= $e2['telefone']; ?></p>
</div>
使用该代码切换 p 的可见性将使用以下代码
$('.phone a').on('click', function(e){
$(this).next().toggle('slow'); // this refer to the A tag that was clicked, and .next() selects the next element on the DOM, which in this case is the P tag
e.preventDefault(); // it is a good thing to use to avoid the default behavior of the A tag
});
有关树遍历方法的更多信息,请访问:http://api.jquery.com/category/traversing/tree-traversal/
$("a").click( function(){
var myId = $(this).prop("something that gives you the corresponding id, like a classname");
$("#"+myId).slideToggle('slow');
});