JQuery的值不会改变

JQuery Values are not changing

本文关键字:改变 JQuery      更新时间:2023-09-26
 @Html.ActionLink("Search", "GetDateWiseGuestReport", "Reports", new { StartDate = "sss",EndDate="eee" }, new { @id = "btnDateWiseGuestSearch",  @class = "btn btn-red" })

$("#btnDateWiseGuestSearch").bind('click', function () {
                //Get the id of the selected item in dropdown
            var EndDate = $("#txtDateWiseGuestEndDate").val();
            var StartDate = $("#txtDateWiseGuestStartDate").val();
              this.href = this.href.replace("sss", StartDate);
              this.href = this.href.replace("eee", EndDate);
 });

好的,我使用上面的代码在运行时更改操作链接URL。一切都很顺利。但是我有一个奇怪的问题,即当我第一次点击按钮时,它从文本框中获取值并相应地改变,但是当我再次按下按钮时,它不会从文本框中获得新值,而不是以某种方式使用我第一次输入的旧值!

因为在第一次点击之后,您将从href中替换ssseee,因此在href中没有ssseee。所以在第一次点击

之后没有任何内容被替换

所以一个可能的解决方案是将原始的href值存储在其他地方,然后使用它来替换内容。在下面的解决方案中,data api用于存储原始值

var $btn = $("#btnDateWiseGuestSearch");
$btn.data('href', $btn.attr('href'))
$btn.bind('click', function () {
    //Get the id of the selected item in dropdown
    var EndDate = $("#txtDateWiseGuestEndDate").val();
    var StartDate = $("#txtDateWiseGuestStartDate").val();
    var href = $(this).data('href');
    this.href = href.replace("sss", StartDate).replace("eee", EndDate);
});

基本上在你的jQuery代码中你通过替换ssseee来创建一个新的链接但是一旦你替换了它们,你就不会再找到它们了

this.href = this.href.replace("sss", StartDate); // sss no longer exists after this
this.href = this.href.replace("eee", EndDate); // sss no longer exists after this

你需要做的是在你修改它之前存储原始的href值,然后当你想更新链接

时引用它
$("#btnDateWiseGuestSearch").bind('click', function () {
    var $this = $(this);
    var originalhref = $this.data("href");
    if(!originalhref){
        this.data("href", this.href);
    }
    var EndDate = $("#txtDateWiseGuestEndDate").val();
    var StartDate = $("#txtDateWiseGuestStartDate").val();
    this.href = originalhref.replace("sss", StartDate).replace("eee", EndDate);
 });