开发者

why this javascript code is not working?

Do you know why this is failing, I mean alert is working (it shows me that if found the button) but text or background is not changed:

    $('input[type=button]').click( function() {

    var button=document.getElementsByName("contactme");
    alert(button.length + " elements!");
    button.value="New Button Text";
   button.style.backgroundImage="url(some_real_gif);"
});

HTML:

<i开发者_运维问答nput type="button" name="contactme" value="test"/>

Thanks...

I have to use plain java script not jQuery..


You're setting value and style of a NodeList. getElementsByName can retrieve multiple elements, as the name attribute does not have to be unique in the document (the clue's in the name!) Setting these has no effect -- it doesn't affect the properties of the element(s) within the NodeList.

Either loop through the element(s) manually (using a for loop) or fully use jQuery:

$('input[type=button]').click(function () {
    var buttons = $('input[name="contactme"]');
    alert(buttons.length + " elements!");
    buttons.val("New Button Text");
    buttons.css({backgroundImage: "url(some_real_gif)"});
});

See the jQuery API:

  • val
  • css
  • attribute-equals selector ([name="value"])


It looks like var button=document.getElementsByName("contactme"); would return an array of elements. Try:

var button=document.getElementsByName("contactme")[0];


getElementsByName will return a nodeList but value and style are properties of HTMLElementNodes. You have to loop over the list to get them.


$('input[type=button]').click(function() {
     $("#contactme").val('New Button Text').css('background-image', 'url(some_real_gif)');
});

You would need to make sure the button id matches the name...


Because button is a list of elements (even if it is a list of one)

What you can do is use button[0].value and button[0].style.background

Or use a jQuery solution:

To change only clicked button:

$('input[type=button]').click( function() 
{
    $(this).val("New Button Text");
   $(this).css('background-image','url("some_real_gif")');
});

To change all buttons:

$('input[type=button]').click( function() 
{
   $('input[type=button]').each(function(){
        $(this).val("New Button Text");
        $(this).css('background-image','url("some_real_gif")');
    });
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜