简体   繁体   中英

document.getElementById onclick only working once per page load

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 page?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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