javascript - 使用 href 值查找 anchor 标记并使用新的 href 值更改 href 值

标签 javascript html jquery jquery-events

这是html代码:

<td>
<a class="buttontext" href="/kkdmpcu/control/MilkDeliveryScheduleReport.txt?shipmentId=10306&amp;reportTypeFlag=milkDeliverySchedule" target="_blank" onclick="javascript:setSelectedRoute(this, 10306);" title="Milk Delivery Schedule">Delivery Schedule</a>
</td>
<td>
<a class="buttontext" href="/kkdmpcu/control/KVGenerateTruckSheet.txt?shipmentId=10306&amp;reportTypeFlag=abstract" target="_blank" onclick="javascript:setSelectedRoute(this, 10306);" title="Abstract Report">Route Abstract Report</a>
</td>

我有 href 值。使用 href 值,我应该找到 anchor 标记并使用 jQuery 将 href 值更改为新值。这是我目前无法正常工作的代码:

$('a[href$=(existingUrl)]'); // existingUrl is the href value I have
    .attr('href', resultUrl);  // resultUrl is the url that I need to replace with existingUrl.
  
//The whole code I have Right now

function setSelectedRoute(existingUrl, shipmentId) {
         
        var updatedUrl = existingUrl.toString();
        var facilityIndex = updatedUrl.indexOf("facilityId");
        
        if(facilityIndex > 0){
            updatedUrl = updatedUrl.substring(0, facilityIndex -1);
        }
        var form = $("input[value=" + shipmentId + "]").parent();
        var routeId = form.find("option:selected").text();
        var resultUrl = updatedUrl + "&facilityId=" + routeId;
        alert(resultUrl);
        
        $('a[href='+existingUrl+']').attr('href', resultUrl);   
    }

最佳答案

您不应该在选择器和 attr 方法之间使用分号,如果 existingUrl 是一个变量,您应该将其连接起来,试试这个:

$('a[href="'+existingUrl+'"]').attr('href', resultUrl);

关于javascript - 使用 href 值查找 anchor 标记并使用新的 href 值更改 href 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12018925/

相关文章:

javascript - 悬停时更改 div 的内容,jQuery

html - 静态html站点的浏览器cookies有什么作用吗?

html - 如何使用 getUserMedia 获取网络摄像头图像的大小?

javascript - 动画 Div 展开到全屏

javascript - 完整日历点击事件谷歌日历的时间错误

javascript - jQuery .data 可以使用破折号访问驼峰式大小写键

javascript - 缓存 css 属性名称的通用函数

javascript - 动态添加 Remove font awesome in to span?

javascript 拆分和 JSON.parse

javascript - jquery ajax返回值和done函数