HTML: 我附上了我所面临问题的简化示例:
<h2>Product2</h2>
<div id="products">
<a class="my-product1" href="#"><span>my-product1<span></a>
<a class="my-product2" href="#"><span>my-product2<span></a>
<a class="my-product3" href="#"><span>my-product3<span></a>
<a class="my-product4" href="#"><span>my-product4<span></a>
<a class="my-product5" href="#"><span>my-product5<span></a>
</div>
Javascript: 我已经从页面标题中提取 myProduct 并强制使用小写。接下来,我尝试根据其类别从链接组中删除该产品。这很可能是 jquery101 但是我不知道如何使用变量来将类添加到链接来确定要选择哪个类。在此示例中,假设 var myProduct = Product2
function removeProduct(myProduct){
$("a.myProduct").addClass("display-none");
};
此外,我仍在学习中,因此如果您有时间,简要解释一下为什么我所做的事情是错误的,将会大有帮助。感谢您的宝贵时间!
最佳答案
只需将类名连接到选择器字符串:
$("a."+variable)...
<小时/>
根据您的要求提供额外信息:
不要使用“display-none”类...更改其名称或使用隐藏元素的 jQuery native 代码(hide
( docs ))
function removeProduct(myProduct){
$("a." + myProduct).hide();
};
使用 css
( docs ) 函数更改 css 规则:
function removeProduct(myProduct){
$("a." + myProduct).css('display', 'none');
};
使用addClass
函数添加类:
function removeProduct(myProduct){
$("a." + myProduct).addClass('someClass');
};
将 myProduct
和 removeProduct
名称更改为更有意义的变量名称:
function hideAnchorElement(className){
$("a." + className).hide();
}
关于javascript - 使用 jquery 1.4 或 javascript 如何使用变量定位特定链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9788303/