Jquery: value on $.取决于所选链接的帖子

jquery: value on $.post that depends on link selected

本文关键字:链接 取决于 value on Jquery      更新时间:2023-09-26

我的应用程序中有一个带有两个超链接的页面。这两个超链接都将用户重定向到同一个页面,在那里他们可以为新帐户添加信息。当选择链接#1时,传递给控制器动作的一个值必须为1。如果选择了另一个链接,则值为2。如何使用jquery做到这一点?

超链接:

<div style="position:absolute; width:100px; top:25%; left:50%; font-family:Arial; font-weight:bold; white-space:nowrap ">
    <a href="~/rxcard/addaccount" style="color:#444444;">ADD CLINIC</a>     
</div>
<div style="position:absolute; width:100px; top:33%; left:48%; font-family:Arial; font-weight:bold; white-space:nowrap">
    <a href="~/rxcard/addaccount" style="color:#444444;">ADD MEDICAL OFFICE</a>
</div>

为什么需要使用jQuery呢?使用简单的GET参数

<a href="~/rxcard/addaccount?type=1" style="color:#444444;">ADD MEDICAL OFFICE</a>

注意?type=1传递一个值为1的get参数

在接收页面,您可以使用下面的函数来检查传递了哪个get参数。

function findGetParameter(parameterName) {
    var result = null,
        tmp = [];
    location.search
    .substr(1)
        .split("&")
        .forEach(function (item) {
        tmp = item.split("=");
        if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
    });
    return result;
}

像这样使用:findGetParameter('type')从url中获取type的值。

从这里得到这个函数

为链接添加一个GET参数,它们将继续指向相同的URL,但也会传递一个参数

<div style="position:absolute; width:100px; top:25%; left:50%; font-family:Arial; font-weight:bold; white-space:nowrap ">
    <a href="~/rxcard/addaccount?param=1" style="color:#444444;">ADD CLINIC</a>     
</div>
<div style="position:absolute; width:100px; top:33%; left:48%; font-family:Arial; font-weight:bold; white-space:nowrap">
    <a href="~/rxcard/addaccount?param=2" style="color:#444444;">ADD MEDICAL OFFICE</a>
</div>

你应该定义一个新的属性,比如data-id你的html元素,然后检测点击动作并改变href.

<div>
    <a href="~/rxcard/addaccount" data-id='1'>ADD CLINIC</a>     
</div>
<div>
    <a href="~/rxcard/addaccount" data-id='2'>ADD MEDICAL OFFICE</a>
</div>
<script>
$("a").on('click',function(){
    var thiz = $(this);
    thiz.attr('href',thiz.attr('href')+?val=thiz.attr('data-id'));
});
</script>

如果你在初始化中有值,你可以给不同的href你的锚。在这种情况下,你不需要Jquery或Javascript;

<div>
    <a href="~/rxcard/addaccount?val=1">ADD CLINIC</a>     
</div>
<div>
    <a href="~/rxcard/addaccount?val=2">ADD MEDICAL OFFICE</a>
</div>