开发者

Javascript HREF updating

I have some URLs I visit occasionally that have page numbers indicated in the HREF. These change and I need to keep track of the last one visited. I have been doing this by cutting-pasting into a text file, but want to replace this with a local HTML page that I can update with javascript. Here is an example I created:

<script type="application/javascript">
      function update(n,newvalue) {
           var link = document.getElementById('l' + n);
           var href = link.getAttribute('href', 2);
           var textfield = document.getElementById('p' + n);
           var parts = new Array();
           parts = href.split('-');
           parts[1] = 'p' + newvalue;
           textfield.setAttribute('value', newvalue);
           var newhref = parts.join('-');
           link.setAttribute('href',newhref);
       }
</script>
<form>
     <dl>
         <dt><a target="_blank" id="l1" href="http://foobar.org/t5-p8-data.html">Task 5 Data<a></dt>
         <dd>Page: <input type="text" id="p1" value="8" onChange="update(1,this.value)" /> </dd>
     </dl>
</form>
    </html>

When I enter a new value in the text field and trace through this with Firebug it seem开发者_高级运维s to work fine, i.e. the link href value and the textfield value get changed in the DOM, but when the function exits they are back to the original values in the page. What am I doing wrong?


MAJOR EDIT:

The problem is that a hitting enter in a single <input> inside a form tag will submit the form, so what happens is, you type in the input, hit enter, which causes a blor, so the onchange event fires and everything shows up fine in the debugger. When that finishes, the page reloads (since the default form action is to GET the current page) without flicker, resetting the input value.

Solution 1: Remove the <form> tags. The form element isn't doing anything useful in this snippet.

Solution 2: Add an onsubmit=return(false) attribute to the <form>.

Solution 3: Add another non-hidden input to the form.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜