简体   繁体   中英

How to move image from one table's cell to another table's cell when clicked

I know it sounds very basic, but I am new to Javascript.

Here is my problem: I have two tables - Table1 has only one cell and table2 has one row and 4 columns, containing 4 images (clickable). What I want to do is when I click on any of the images, it should go to the cell of Table1. If I click on another image (in Table2), it should replace the first image in Table1 with the second image.

I think we need two methods in Javascript - one for moving the image and another for retrieving the image in the cell of the table.

Any help is always helpful.

$('#table1 tr td').click(function(){
$('#table2 tr td').html(this.html());    

});

Javascript

define onclick="copyimage(this.innerHTML)" on every td of tabl1

function copyimage(thehtml)
{
 var x=document.getElementById("table2ID").rows[0].cells;//you can replace 0 with row index if you have more than one rows

 x[0].innerHTML=this.innerHTML;//you can replace 0 with cell index if you have more than one cells

}

I'm going to walk you through it without writing the code for you.

Say you have two tables, tableA and tableB . They will both have a tbody with a tr *. tableA will only have a td cell; tablB will have four td` cells.

* tr is a "table row", td is table data since tables were designed for the most part to hold data.

Using Document Object Model (DOM) methods, you will need to find and select the element's DOM node within the document object. To do so, the easiest way is to put an id attribute on the elements you're trying to find. Keep in mind, id attributes should be unique to the page ( no dupes! ). This means <img id="imageLanding" src="..."> and <img id="image1" src="..."> , <img id="image2" src="..."> , etc. is what you will end up with for the img elements.

Sidenote: HTML5 allows id s to be id="1" , but I consider this a bad practice and recommend not using that form. It's a principle thing.

By this point you should have table markup that approximates:

table
    tbody
        tr
            td
                img id="imageLanding"
table
    tbody
        tr
            td
                img id="image1"
            td
                img id="image"
            td
                img id="image3"

... etc ...

DOM elements have properties ("attributes" have a slightly different meaning) and methods. An img element will have a src="..." attribute, for instance, which in this case has a corresponding element.src property on the img DOM element. The attribute is what you gave the parser when the page laoded, and the property is what the attribute becomes in the element as a DOM node. In some cases, the properties accessed may not update in the way you would think, which is why there is a distinction.

Next, take a moment to consider what's going to occur using your description of events. Someone will be presented with two tables and the option to click the images in one table will be provided to them , after which the function will swap the clicked image with the other table's one image. Bold text identifies everywhere where an action took place, either in setup or execution. (Removing the clicked image from it's td and moving it to the other table after the other image is removed is another approach; I'm not demonstrating that here).

So you have to wait for "something" to happen before acting. This "something" is an event . All DOM elements support events of some kind (not all the same events occur on every type of element, though), which allow you to do something when something happens : ONclick , ONmouseover , ONmouseout , etc. Caps intended. It's "on" an event occurring. Consider:

On arriving home from school, I ate a sandwich.

Note, if you are using attributes or direct DOM properties to setup your event handler with an element, you need to append on to each of those event names. In other words, onclick , onmouseover , and onsubmit , which is for working with form elements before they are submitted.

Using DOM methods (preferred to onclick="stuff()" ) would mean in practice:

element.onclick = function(){};`

That form of a function you see there is called a variable function and when used in that way returns a value to the variable or property to the left of it. Doing that allows you to call that function with the variable name and () added, ie, myVar.myFunc() or as depicted here, element.onclick() .

Note, there is another ("better" by a degree or so) way to "attach" events to elements, but I don't want to confuse you with too many options. You can also use a function name(){} format to declare, and then use it's reference such as element.onclick = name; . Note, when I do this, no () are used . Otherwise you're calling the function immediately and passing it's returned result to the variable. In most cases, you don't want to do it this way.

Now, you have the general idea of the layout of the two table's markup and "events". Taking the two together, we have five elements with identifiers. The DOM method for finding these elements is:

var img1 = document.getElementById('image1');

Feed a different id into that, you get a reference to the element's DOM node. At that point, you can manipulate it, get stuff from it like property values, and assign it a special event that is told to "handle" that event when it occurs on that element. For instance:

img2.onclick = function(){
    alert('You clicked image ' + this.id);
};

Or passing a function declaration's reference to the event handler property:

function alertID(){
    alert('You clicked image ' + this.id);
};

img2.onclick = alertID;

If you use a DOM element property to set an event handler, you can then use this inside of that function to self-reference, ie, get information on the element that called the function. Inside that function at that time you are within the "context" of that element.

Using tag attributes to attach event handlers, you end up with this cruft, which is boring and not so fun:

<img id="image1" onclick="whyme(this)"/>

function whyme(el){
    alert('You clicked image ' + el.id);
};

Or, perhaps not fatally but certainly painful to see, pass a value "identifying" your element:

<img id="image1" onclick="whyme('image1')"/>

function whyme(id){
    alert('You clicked image ' + document.getElementById('id').id;
};

Certainly roundabout.

So at this point, you have to put those pieces together. You have your markup for your tables in your body tag, you have an understanding that you need to "follow an event with an action" contained in a function, and you know you need to do something to swap the images.

A note about page loading and parsing. As the page loads, if you try to run a script to call an element, that element has to have been before the script in parse order (top to bottom) as the page loads, or you have to wait until the page is initially parsed, after which the DOM is constructed and now any element you want to, you can access freely (more or less). jQuery and other languages use a custom ready event, but that event doesn't actually exist in the DOM as a method.

So you can't use that onready business in plain DOM. What you can use is:

window.onload = function(){};

That will fire after the page has been parsed. onready may fire before or after onload , because it's detecting if the DOM is ready by monitoring something else independently. For regular DOM methods, don't worry about it at this point.

The two affected img tags are parsed and turned into DOM elements. So you know you can select them (using an id attribute and a DOM document method), save them to a variable or object/element property, and then... drum roll... You can access properties and methods on that element as well to make your intended result occur.

Now, the page has loaded, markup is parsed, you have a script to run when the onload event has been triggered, and now what? Well, you write the code. What you want to do when the mouse clicks on one of the elements you've told to specially "handle" is:

[Function swapImages() is called and executed when mouse is clicked]
    Get the imageLanding element reference

    With the imageLanding element's reference
        Set a variable to be equal to the img tag's src attribute, img.src

    Using the clicked element's reference (hopefully this)...
        Set the imageLanding's img.sr equal to the clicked element's src attribute

    Set the clicked element's this.src = the saved value you put in the variable 

    return to the awaiting events state
[Function ends]

That's it, more or less. I know it sounds like a lot, but it get easier the more times you do it. What you're trying to do has several methods for getting there (such as swapping the element's parent markup value in the DOM as CodeAddict demonstrated), but this is by far the simplest method for this and has almost the same effect (to your purposes, the same).

Once you learn some more, you can do things like dynamically seek, detect and manipulate events and other related actions performed on and with elements, without knowing much or anything about them beforehand, from within your code.

But for now don't worry about that level. Try this. And then use MDN's tutorials .

$('#table1 tr td img').click(function()
{
  $(this).clone().appendTo($('#table2 tr td'))
  $(this).remove();
})

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