簡體   English   中英

從錨標記獲取元素ID並替換href

[英]Getting element id from anchor tags and replace href

我有一個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_id,並將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獲取正在查看的當前項目的別名。

添加此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");

假設你有一個array{category_id:"someValue", category_alias:"someValue"} myArr在你的JS(也許你可以使用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);
}

我沒有時間進行測試,所以如果我錯了,請隨時糾正我。

哇! 很抱歉給我打擾。.但是我必須做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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM