简体   繁体   English

使用href值查找锚标记,并使用新的href值更改href值

[英]find anchor tag using href value and change href value with new href value

This is the html code 这是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>

I have the href value. 我有href值。 Using href value I should find the anchor tag and change the href value to new value using jquery. 使用href值,我应该找到定位标记,并使用jquery将href值更改为新值。 This is the code I currently have which is not working. 这是我目前无法使用的代码。

$('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);

this is not the href attribute, it is the a tag itself, that is first mistake, therefore existingUrl will get the object instead. this是不是href属性,它是a标签本身,也就是第一个错误,因此existingUrl将获得的对象,而不是。

change the code like 像这样更改代码

function setSelectedRoute(existingUrl, shipmentId) {

        var updatedUrl = $(existingUrl).attr('href'); // first instance
        // or var updatedUrl = existingUrl.getAttribute('href');

        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')+'"]').attr('href', resultUrl);  //second instance
    }

for the second instance, you can directly use existingUrl 对于第二个实例,您可以直接使用existingUrl

$(existingUrl).attr('href', resultUrl);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM