开发者

document.getElementById onclick only working once per page load

开发者 https://www.devze.com 2023-04-08 17:15 出处:网络
I have a link: <a id=\"lnk\" href=\"${pageContext.request.contextPath}/path/path2.pdf?var0=sometext&var1=moretext\" onclick=\"update();\"target=\"_blank\">click to export</a>

I have a link:

<a id="lnk" href="${pageContext.request.contextPath}/path/path2.pdf?var0=sometext&var1=moretext" onclick="update();"target="_blank">click to export</a>

and a JavaScript function in a separate file:

function update()
{
    var link = document.getElementById("lnk");
    link.href += "&var2=" + document.getElementById("textareaIdName").value;
    return;
}

This is supposed to grab the text from a textarea box in a jsp form to pass into controller for output. It works the first time I click the link, but then if I change the text in the box and click link again it holds the same value from the first click on every other link click until I reload the page regardless of what I change in the text box. The link returns a file download.

How can I keep getting new text from textarea without reloading the pag开发者_运维知识库e?


This occurs because you are using += each time the link is pressed which will keep concatinating the var2 onto the end of the hyperlink, to make this work you should use:

var linkName = "${pageContext.request.contextPath}/path/path2.pdf?var0=sometext&var1=moretext";

function update(obj) {
    obj.href = linkName + "&var2=" + document.getElementById("textareaIdName").value;
    return;
} 

<a id="lnk" href="" onclick="update(this);" target="_blank">click to export</a>


In your html:

<a ... onclick="return update(this);">click me</a>

Passing this in the handler means that this in the function references the DOM element, so you don't have to use getElementById, so the function is:

function update(link) {
    link.href = /* whatever */;
}

Now you can put the handler on multiple elements without knowing or using the id.

0

精彩评论

暂无评论...
验证码 换一张
取 消