我有一个 Joomla 项目,在更改下拉菜单列表中的链接时遇到了一些小问题。
我有这个菜单及其子菜单。
商店
- 第一只猫
- 第二只猫
- 第三只猫
HTML:
<ul class="level2">
<li>
<a id="firstcat" href="/my_website/index.php/shop/firstcat">First Cat</a>
</li>
<li>
<a id="secondcat" href="/my_website/index.php/shop/secondcat">Second Cat</a>
</li>
<li>
<a id="thirdcat" href="/my_website/index.php/shop/thirdcat">Third Cat</a>
</li>
</ul>`
Joomla 中默认菜单项链接到其类别别名。但我想将菜单链接到它们的category_id。现在,我想获取它们不同的id,并在数据库中找到它们相应的category_ids并替换href
进入他们的category_id。
像这样:
<a id="firstcat" href="/my_website/index.php/shop?16">FirstCat</a>
<a id="secondcat" href="/my_website/index.php/shop?17">SecondCat</a>
<a id="thirdcat" href="/my_website/index.php/shop?18">ThirdCat</a>
我只想通过 JavaScript 或 jQuery 来完成此操作,因为在 Joomla 中挖掘文件并将别名替换为 id 需要时间。
目前,我仅手动执行此操作。
$('ul.level2 li a#firstcat').attr('href','/my_website/index.php/shop?catid=16');
$('ul.level2 li a#secondcat').attr('href','/my_website/index.php/shop?catid=17');
$('ul.level2 li a#thirdcat').attr('href','/my_website/index.php/shop?catid=18');
在 php 部分,我必须获取他们的category_id 是这样的。
<?php<br/>
echo $menuItem->alias . '<br/>';<br/>
$db = & JFactory::getDBO();<br/>
$db->setQuery('SELECT id FROM #__k2_categories WHERE alias="' . $menuItem->alias . '"');<br/>
$result = $db->loadResult();<br/>
echo $result;<br/>
foreach ($result as $res) {<br/>
echo $res->id;<br/>
}<br/>
?>
$menuItem->alias
-> 获取当前正在查看的项目的别名。
最佳答案
假设您的 JS 中有一个 {category_id:"someValue",category_alias:"someValue"}
myArr
的数组
(也许您可以通过 ajax 调用得到这个,不管你怎么做)
做类似的事情
var length = myArr.length;
for(var i = 0 ; i < length ; i++) {
$("#" + myArr[i].category_alias).attr("href","/my_website/index.php/shop?" + myArr[i].category_id);
}
我没有时间测试这个,所以如果我错了,请随时纠正我。
关于javascript - 从 anchor 标记获取元素 id 并替换 href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19489121/