开发者

jQuery: copying element attributes to another attribute of the same element

I've got a list of links, all in the same class, each with a custom argument ("switch-text"). My script should copy the text of the custom argument to the text of each link and re开发者_JAVA百科place it ("Pick A" should become "Pick A Please").

It works fine with only 1 link, but when I add several, they all get switched to the first argument. ("Pick B" should be replaced by "Pick B Please", but it doesn't).

I could probably solve this using each(), but I'm preferably looking for a simple, single jQuery line that does it, and I'm baffled I haven't yet found out how to achieve this.

Can somebody help? Thanks!

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
  $(".switcher").text( $(".switcher").attr("switch-text") );
});
</script>
<a href="a" class="switcher" switch-text="Pick A Please">Pick A</a><br>
<a href="b" class="switcher" switch-text="Pick B Please">Pick B</a><br>


You should use each to go through all the elements, and use this to always act on the current one.

$(document).ready(function() {
  $(".switcher").each(function(){
    $(this).text( $(this).attr("switch-text") );
  });
});

Demo


Without jQuery you need:

  • Dean Edwards document ready
  • getElementsByClassName

Code:

readyList.push(function() {
  var els = getElementsByClassName("switcher");
  for ( var i = els.length; i--; ) {
    els[i].innerHTML = els[i].getAttribute("switch-text");
  }
});

And change Dean's script to execute functions on document.ready:

function init() {
  // ...
  // do stuff
  for ( var i = 0; i < readyList.length; i++ ) {
    if ( typeof readyList[i] === "function" ) {
      readyList[i]();
    }
  }
  //..
}

That's it. You've saved a lot of bandwidth. :)

Demo without jQuery


0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜