简体   繁体   English

使用Javascript / jQuery以编程方式将当前锚点/散列/片段附加到任何表单操作URL

[英]Append programmatically current anchor/hash/fragment to any form action url with Javascript/jQuery

I have a JSP with some external API custom taglibs that handle URLs with hash (I know serverside does not handle them per se). 我有一个带有一些外部API自定义taglibsJSP ,它使用hash处理URL(我知道服务器端本身不处理它们)。

I am trying something like this 我正在尝试这样的事情

$(document).ready(function(){
    $('form').prop('action').append(window.locator.anchor)
});

But I am doing it wrong and I am not sure if it is the best way anyway. 但我做错了,我不确定这是不是最好的方式。 Could you help me? 你可以帮帮我吗?

There is no reason to do this because the hash is never sent to the server. 没有理由这样做,因为哈希从不发送到服务器。 But here is how you could do it: 但是你可以这样做:

$('form').prop('action', function(i, val) {
    return val + window.location.hash;
});

There are a couple of things which are not correct in your code: 您的代码中有一些不正确的事情:

  • .prop(name) [docs] returns the value of that property which is often a string. .prop(name) [docs] 返回该属性的值,该属性通常是一个字符串。

  • .append [docs] is a jQuery method to append a DOM element to another element. .append [docs]是一个将DOM元素附加到另一个元素的jQuery方法。 It is not a string method and cannot be used to concatenate strings. 不是字符串方法,不能用于连接字符串。

  • window.locator.anchor does not exist. window.locator.anchor不存在。 window.location [MDN] holds information about the current URL and it has a property hash which refers to the fragment identifier of the URL. window.location [MDN]保存有关当前URL的信息,它有一个属性hash ,它引用URL的片段标识符。

I recommend to have a look at the jQuery documentation . 我建议看一下jQuery文档 It has examples for each method. 它有每种方法的例子。 You also have to learn some elementare JavaScript to be able to perform simple operations such as string concatenation. 您还必须学习一些elementare JavaScript才能执行简单的操作,例如字符串连接。

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

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