开发者

Javascript href link counter [closed]

开发者 https://www.devze.com 2023-01-04 03:40 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.

I need to make a button that increments and decrements a variable. When you click a link it increments a variable in the link href.When you click another link it decrements a vari开发者_StackOverflowable in the link href.The variable can only go up to the last number in a specified array.PHP will be embedded around it. Any ideas?

<script type="text/javascript">
var counter = 0;
document.write('<button onclick="counter++">Increment</button>');
document.write(counter);
</script>

This is an abomination I know, and it uses a button.


I'm going to make a whole lot of assumptions, including that you can use jQuery. It can be done without it, but it's simply easier to write with it. The only real jQueryness that I'm using is applying the handlers -- adjust this as necessary for another framework or to use pure javascript. Also, I assume that the base link doesn't have any existing query parameters and that you're adding the count as a query parameter. Again, adjust as necessary to reflect how you want the url built.

<a class="link" href="http://example.com/somecontroller/someaction">Click Me</a>
<button class="increment">Increment</button>
<button class="decrement">Decrement</button>

<script type="text/javascript">
   $(function() {
       var counter = 0;
       var max = <?php echo count($arr) >;
       $('button.increment').click( function() {
            ++counter;
            if (counter > max) counter = max;
       });
       $('button.decrement').click( function() {
            --counter;
            if (counter < 0) counter = 0;
       });
       $('a.link').click( function() {
            window.location = $(this).attr('href') + '?count=' + counter;
            return false; // important to stop the default link action
       });
   });
</script>
0

精彩评论

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