Two points of attention for jQuery and two points of attention for jquery
Problem:
I want to write a component that dynamically loads input problems and options ,:
Initialization status:
Running effect:
Question 1:
When you click "add question", add a large node dynamically. A "add option" button is next to each problem. You need to add an event to this button and click to add the option node. Adding events to such buttons during initialization is not feasible, because the events loaded in page 1 are invalid for the nodes that are dynamically added, so you need to bind an event. There is a problem! Because the events you bind will be bound to the existing nodes again, you can click the previous button and trigger multiple times. Therefore, we need to clear all previous events before binding the events of the new node to ensure that there is only one binding event for all buttons on the page. The solution code is as follows:
$(".addOption").unbind("click");$(".addOption").click(function(){addOption(this);});
Question 2:
When you delete an option, you need to sort the subsequent options. The value 1234 indicates that 2 is deleted, and the value 123 indicates that the option is deleted.
At the beginning, my processing was: Click the delete option button to remove the parent node of the node, that is, the entire option area (the event is bound to the <a> area ), obtain the parent node of the node, and then obtain all the child nodes. Now we know there are several options. The problem is that the node cannot be obtained from the dead or dead, and it is impossible to obtain any parent node. If this node is deleted, it will not exist. How can we obtain the parent node. Therefore, you must obtain the parent node of the parent node before deleting the option. And then proceed.
function delOption(node){var optsAreas = $(node).parent().parent();$(node).parent().remove();var options = $(optsAreas).children();var optsLength = $(options).length;var i = 1;$(options).each(function(){$(this).find('.order-option').html(i);if(i<optsLength){i++;}});}
Here is my personal experience in solving practical problems. It may not be very rigorous in solving the problems. Please contact me.