简体   繁体   中英

img src attribute changing

I have a table of blank images, which on click I'd like to change. So, I'm creating a table with:

table_string = "<center><table border=1>";
for( i = 0 ; i < 8 ; i++ )
{
    table_string += "<tr>";
    for( j = 0 ; j < 8 ; j++ )
    {
        table_string += "<td><img name=image"+i+"_"+j+" src=games/graphics/atoms/blank.jpg onclick='OnClick("+i+","+j+")'></td>";
    }
    table_string+="</tr>";
}
table_string+= "</table></center>";
$("#atoms_board").append(table_string); //appending the html code to atoms_board div,

And now the OnClick function in which im trying to change the src attribute:

function OnClick( i, j )
{
    $('input[name=image"+i+"_"+j+"]').attr('src');
}

My problem is that function OnClick doesn't change the img's src ;/. I saw here many similiar problems, but everywhere i found only this answer. Any help appreciated : }.

Note the syntax highlighting in the bottom snippet. See how it's all one color? You are encoding your logic into the string. This means you string is this:

'input[name=image"+i+"_"+j+"]'

Instead of this:

'input[name=image1_2]'

Try:

$("input[name=image"+i+"_"+j+"]").attr('src');
//^ big quote                  ^ big quote 

See how the variable turn black in the syntax highlighting now? That means they are no longer considered literally part of the string.

If you aren't using an editor with syntax highlighting, I highly suggest you find one. They help you find this sort of problem.

Pass a reference to itself using "this".

onclick="OnClick(this)"


OnClick function(element) {
      alert(element.src)

}

There is one issue in your code. Modify it to

function OnClick( i, j )
{
    $('input[name=image'+i+'_'+j+']').attr('src');
}

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