简体   繁体   English

单击时如何将图像从一个表的单元格移动到另一张表的单元格

[英]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. 我知道这听起来很基础,但是我是Java语言的新手。

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). 这是我的问题:我有两个表-Table1只有一个单元格,而table2有一行和4列,其中包含4个图像(可单击)。 What I want to do is when I click on any of the images, it should go to the cell of Table1. 我想做的是,当我单击任何图像时,它应该转到Table1的单元格。 If I click on another image (in Table2), it should replace the first image in Table1 with the second image. 如果单击另一张图像(表2中的图像),则应将第二张图像替换表1中的第一张图像。

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. 我认为我们需要Javascript中的两种方法-一种用于移动图像,另一种用于在表格的单元格中检索图像。

Any help is always helpful. 任何帮助总是有帮助的。

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

});

Javascript Java脚本

define onclick="copyimage(this.innerHTML)" on every td of tabl1 在tabl1的每个td上定义onclick="copyimage(this.innerHTML)"

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 . 假设您有两个表tableAtableB They will both have a tbody with a tr *. 他们都将有一个tbodytr *。 tableA will only have a td cell; tableA将只有一个td单元格; tablB will have four td` cells. tablB will have four td`单元。

* tr is a "table row", td is table data since tables were designed for the most part to hold data. * tr是“表行”, tdtable data因为表是为保存数据而设计的。

Using Document Object Model (DOM) methods, you will need to find and select the element's DOM node within the document object. 使用文档对象模型(DOM)方法,您将需要在文档对象中查找并选择元素的DOM节点。 To do so, the easiest way is to put an id attribute on the elements you're trying to find. 为此,最简单的方法是在您要查找的元素上添加id属性。 Keep in mind, id attributes should be unique to the page ( no dupes! ). 请记住, id属性应该是页面唯一的( 不要重复! )。 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. 这意味着<img id="imageLanding" src="..."><img id="image1" src="..."><img id="image2" src="..."> ,等,这将是img元素的最终结果。

Sidenote: HTML5 allows id s to be id="1" , but I consider this a bad practice and recommend not using that form. 旁注:HTML5允许idid="1" ,但是我认为这是一种不好的做法,建议不要使用该形式。 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. DOM元素具有属性(“属性”的含义略有不同)和方法。 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. 例如,一个img元素将具有src="..."属性,在这种情况下,该属性在img DOM元素上具有一个相应的element.src属性。 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. 属性是页面加载后为解析器提供的内容,而属性是属性作为DOM节点出现在元素中的内容。 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). (去除它被单击图片的td和其他图像被删除后,将其移动到另一台是另一种方法,我没有证明这里)。

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. 所有DOM元素都支持某种类型的事件(尽管并非所有相同类型的事件都会在每种类型的元素上发生),这使您可以在发生某些事情时做一些事情ONclickONmouseoverONmouseout等。 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. 请注意,如果您正在使用的属性或直接DOM属性设置你的事件处理程序的元素,你需要附加on每个这些事件的名称。 In other words, onclick , onmouseover , and onsubmit , which is for working with form elements before they are submitted. 换句话说, onclickonmouseoveronsubmit ,用于在提交表单元素之前对其进行处理。

Using DOM methods (preferred to onclick="stuff()" ) would mean in practice: 实际上,使用DOM方法(首选onclick="stuff()" )意味着:

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() . 这样一来,您就可以在添加了变量名和()下调用该函数,即myVar.myFunc()或此处所示的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; 您还可以使用function name(){}格式进行声明,然后使用其引用,例如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: 查找这些元素的DOM方法是:

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

Feed a different id into that, you get a reference to the element's DOM node. 输入一个不同的ID,您将获得对该元素的DOM节点的引用。 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. 如果使用DOM元素属性设置事件处理程序,则可以在函数内部使用this函数进行自引用,即获取有关调用该函数的元素的信息。 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. 您在body标签中具有表的标记,并且了解需要在函数中“跟随事件跟随动作”,并且知道需要做一些事情来交换图像。

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). 在页面加载时,如果尝试运行脚本来调用元素,则该元素必须在页面加载时按解析顺序(从上到下)位于脚本之前,或者必须等到最初对页面进行解析之后,之后即可构建DOM,现在可以构建任何想要的元素,您可以自由访问(或多或少)。 jQuery and other languages use a custom ready event, but that event doesn't actually exist in the DOM as a method. jQuery和其他语言使用自定义的ready事件,但该事件实际上不是DOM中的一种方法。

So you can't use that onready business in plain DOM. 因此,您不能在纯DOM中使用onready业务。 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. onready可能在onload之前或之后触发,因为它通过独立监视其他对象来检测DOM是否已准备就绪。 For regular DOM methods, don't worry about it at this point. 对于常规的DOM方法,此时不必担心。

The two affected img tags are parsed and turned into DOM elements. 解析两个受影响的img标签并将其转换为DOM元素。 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. 因此,您知道可以选择它们(使用id属性和DOM文档方法),将它们保存到变量或对象/元素属性中,然后...鼓式滚动...您可以通过以下方式访问该元素上的属性和方法:好使您的预期结果发生。

Now, the page has loaded, markup is parsed, you have a script to run when the onload event has been triggered, and now what? 现在,页面已加载,标记已解析,当onload事件触发时,您有一个脚本要运行,现在呢? 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). 您尝试执行的操作有几种方法(例如,如CodeAddict所示,在DOM中交换元素的父标记值),但这是迄今为止最简单的方法,并且效果几乎相同(达到您的目的) , 相同)。

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 . 然后使用MDN的教程

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用jquery将焦点移到一个表格单元格中的表格中的文本框到另一个表格单元格 - How to move focus on a textbox in a table which is in one table cell to another table cell using jquery jQuery,在表中单击超链接值时,将其从一个单元格复制到同一行中的另一个单元格 - jQuery, Copy hyper-link value when clicked on it in table from one cell to another in the same row 单击表格单元格或单击图像本身时翻转图像 - Flip an image when a table cell is clicked, or the image itself is clicked 如何使用Javascript将单元格数据值从HTML表格的一列移到另一列? - How to move cell data values from one column to another in HTML table with Javascript? 单击表行时如何从单元格获取值 - How to get the value from a cell when table row is clicked HTML / JS从另一个表单元格更新一个表单元格 - HTML/JS Update one table cell from another table cell 在jQuery中单击后检索表单元格的文本 - Retrieving a table cell's text once clicked in jQuery 在Google Spreadsheets中,如何在用户单击并激活一个单元格后从另一个单元格的值中设置一个单元格的值? - In Google Spreadsheets, how do you set a value of a cell from another cell's value after a user has clicked and activated a cell? 如何从一张桌子的ID中获取一张图片并将其从一个td移到另一个td? - How to get a picture by it's id from a table and move it from one td to another one? 如何<a>使用jQuery在表单元格中</a>更改锚<a>样式</a> - How to change anchor <a> style when it's in table cell using jquery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM