从锚标记中获取元素 ID 并替换 href

Getting element id from anchor tags and replace href

本文关键字:ID 替换 href 元素 获取      更新时间:2023-09-26

我有一个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_alias。但我想将菜单链接到他们的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
echo $menuItem->alias . '<br/>';
$db = & JFactory::getDBO();
$db->setQuery('SELECT id FROM #__k2_categories WHERE alias="' . $menuItem->alias . '"');
$result = $db->loadResult();
echo $result;
foreach ($result as $res) {
echo $res->id;
}
?>

$menuItem->alias -> 获取正在查看的当前项的别名。

假设你的JS中有{category_id:"someValue", category_alias:"someValue"} myArr array(也许你可以通过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);
}

我没有时间测试这一点,所以如果我错了,请随时纠正我。

wew!对不起,打扰了家伙..但是我必须做ajax调用才能让它工作。

我是这样做的。

我的PHP:

$q = $_GET['q'];
$db = & JFactory::getDBO();
$db->setQuery('SELECT id FROM #__k2_categories WHERE alias="' . $q . '"');
$result = $db->loadResult();
if (!empty($result)) {
echo $result;
exit(); }

我的脚本:

<script type="text/javascript">
(function($){
$(document).ready(function() {
$('.level2').click(function(e) {
CurrElId = jQuery(this).attr("id");
$.ajax({
type: 'GET',
url: location.href,
data: 'q='+CurrElId,
success: function(data) {
var basepath = "/mywebsite/index.php/shop";
location.href = basepath+'?'+data;
}
});
e.preventDefault();
});
});
})(jQuery); </script>

添加这个jQuery脚本。

$("#firstcat").attr("href","/my_website/index.php/shop?16");
$("#secondcat").attr("href","/my_website/index.php/shop?17");
$("#thirdcat").attr("href","/my_website/index.php/shop?18");