[英]HTML TAG <A> pass variable both with href and onclick
我希望當有人點擊此鏈接首先訪問我在JS中的函數時,然后按照<a>
標簽中的href函數進行操作。 問題是它首先跟隨href,我無法從js函數傳遞我想要的變量。
這是我的代碼:
PHP
echo '<a href="category.php?id=' . $_SESSION['id'] . '" onclick="myFunction();">
<div class="icon-lock">
<img src="/test/images/lock.png" alt="Locked Button" width="35" height="35" border="0">
</div>';
echo '</a>';
JS
<script>
function myFunction() {
$.ajax({
type: "POST",
data: {id: "1"},
url: "category.php"
});
}
</script>
關於href和myfunction如何工作以打印,我感到非常困惑
$id=$_POST['id'];
echo $id;
頁面重新加載后在PHP中...
有什么想法嗎?
你只需在你的功能上傳遞它
你的PHP代碼看起來像這樣
echo '<a href="category.php?id=' . $_SESSION['id'] . '" onclick="myFunction(this);">/*pass this keyword to function */
<div class="icon-lock">
<img src="/test/images/lock.png" alt="Locked Button" width="35" height="35" border="0">
</div>';
echo '</a>';
function myFunction(str) {
$.ajax({
type: "POST",
url: str.getAttribute("href")
}).done(function() {
// What ever following the link does
window.location.href=str.getAttribute("href")
});
}
您可以在函數中傳遞'id'作為參數,並在ajax成功后使用javascript更改窗口位置。
HTML
<div class="icon-lock">
<img onclick="myFunction(<?=$_SESSION['id']?>)" src="/test/images/lock.png" alt="Locked Button" width="35" height="35" border="0">
</div>
使用Javascript
function myFunction(id) {
$.ajax({
type: "POST",
data: {id: "1"},
url: "category.php",
success: function() {
window.location.assign("category.php?id="+id);
}
});
}
阻止myfunction
方法中的默認操作, myfunction
方法接受事件對象。 然后在成功回調你的ajax請求時,做你想做的事。
<a href="category.php?id=' . $_SESSION['id'] . '" onclick="myFunction(e);">
function myFunction(e) {
e.preventDefault();
$.ajax({
type: "POST",
data: {id: "1"},
url: "category.php"
}).done(function() {
// What ever following the link does
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.