JavaScript - 让多个元素异步闪烁

标签 javascript jquery oop

我有多个 div。如果用户单击其中一个,那么它应该开始闪烁几秒钟,然后返回到正常状态。

它们应该完全独立工作,意味着多个 div 应该能够同时闪烁。

如果只涉及一个div,解决这个问题很容易。但是,如果单击多个 div,则只有一个闪烁,另一个停止......

所以我认为如果我将其编码为面向对象,它会起作用,但它仍然失败,我无法解释原因。

这是我到目前为止的代码,它可能太复杂了,但我需要知道为什么它不起作用,即使我使用了对象。

<强> JSFIDDLE

var OAHelper = new ObjectArrayHelper();

var taskList = new Array();

$(".blinkDivs").click(function() {
	
    var ElementID = $(this).attr("id");
    
    //ElementID is NOT in array
    if (!OAHelper.checkIfObjectExists(taskList, "id", ElementID)) {

        var task = new Task(ElementID);
        var newTask = { id: ElementID, task: task};
        taskList.push(newTask);

		var t = OAHelper.getValue(taskList, "task", "id", ElementID);

		if (t !== false) {
			t.blink();
		}
	}
});



function Task(ElementID)
{
    var self = this;
    this.id = ElementID;
    this.interval = null;
    this.limiter = 0;
    this.toggle = 0;
	this.blink = function()
	{
        $jqElement = $("#" + self.id);

        self.limiter = 0;
        self.interval = setInterval(function() {

            if (self.toggle == 0) {
                $jqElement.css("background-color", "blue");
                self.toggle = 1;
            } else {
                $jqElement.css("background-color", "white");
                self.toggle = 0;
            }

            if (self.limiter > 4) {

                OAHelper.deleteObject(taskList, "id", self.id);
                clearInterval(self.interval);
            }
            self.limiter++;
        }, 400);
	}
}



/**
 * This class provides helper functions to do operations on object arrays
 *
 * functions:
 *
 * delete objects,
 * output objects,
 * change value of specific key,
 * check if specific object exists,
 * check if specific object has specific key value pair
 *
 * Autor: Eduard Fekete
 * @constructor
 */
function ObjectArrayHelper()
{
    /**
     * Runs through all objects of an object array and searches for a record with specific identity.
     *
     * Return Values:
     * 		true	if record exists
     * 		false	if record does not exist
     *
     * Autor: Eduard Fekete
     *
     * @param pObjectArray			Array of objects
     * @param pIdentifier			Identifier Key of the object
     * @param pIdentifierValue		Searched Identifier Value
     * @returns {boolean}
     */
    this.checkIfObjectExists = function(pObjectArray, pIdentifier, pIdentifierValue) {
        for (var i in pObjectArray) {
            for (var key in pObjectArray[i]) {
                if (key == pIdentifier) {
                    if (pIdentifierValue == pObjectArray[i][key]) {
                        return true;
                    }
                }
            }
        }
        return false;
    },

	/**
	 * Runs through all objects of an object array and searches for a record with specific identity
	 * and checks if a specific key has a specific value.
	 *
	 * Return Values:
	 * 		true 	if the value was found in the record,
	 * 		false 	if not.
	 *
	 * Example:
	 * var worker = new Array(
	 *   { id: 1, status: "working" },
	 *   { id: 2, status: "done" }
	 * );
	 *
	 * checkKeyValueInObjectArray(worker, status, "done", "id", 1);		//returns: false
	 * checkKeyValueInObjectArray(worker, status, "done", "id", 2);		//returns: true
	 *
	 * Autor: Eduard Fekete
	 *
	 * @param array pObjectArray	Array of objects
	 * @param string pSearchKey		Key to search for in the objects
	 * @param pCheckValue			The value you are searching
	 * @param string pIdentifier	Identifier Key of the object
	 * @param pIdentifierValue		Searched Identifier Value
	 * @returns {boolean}
	 */
	this.checkKeyValue = function(pObjectArray, pSearchKey, pCheckValue, pIdentifier, pIdentifierValue)
	{
		for(var i in pObjectArray) {
			for (var key in pObjectArray[i]) {

				if (key == pSearchKey) {

					if (pObjectArray[i][key] == pCheckValue) {
						if (pObjectArray[i][pIdentifier] == pIdentifierValue) {
							return true;
						}
					}
				}
			}
		}
		return false;
	},
	/**
	 * Runs through all objects of an object array, searches for a record with specific identity
	 * and sets the target key to the target value.
	 *
	 * Return Values:
	 * 		true 	if the value was set
	 * 		false	if the object was not found
	 *
	 * Autor: Eduard Fekete
	 *
	 * @param pObjectArray			Array of objects
	 * @param pTargetKey
	 * @param pTargetValue
	 * @param pIdentifier			Identifier Key of the object
	 * @param pIdentifierValue		Searched Identifier Value
	 * @returns {boolean}
	 */
	this.setValue = function(pObjectArray, pTargetKey, pTargetValue, pIdentifier, pIdentifierValue)
	{
		for(var i in pObjectArray) {
			if (pObjectArray[i][pIdentifier] == pIdentifierValue) {
				pObjectArray[i][pTargetKey] = pTargetValue;
				return true;
			}
		}
		return false;
	},
	/**
	 * Runs through all objects of an object array, searches for a record with specific identity
	 * and returns the target value.
	 *
	 * Return Values:
	 * 		true 	if get value was successful
	 * 		false	if the object was not found
	 *
	 * Autor: Eduard Fekete
	 *
	 * @param pObjectArray			Array of objects
	 * @param pTargetKey			The target key
	 * @param pIdentifier			Identifier Key of the object
	 * @param pIdentifierValue		Searched Identifier Value
	 * @returns {boolean}
	 */
    this.getValue = function(pObjectArray, pTargetKey, pIdentifier, pIdentifierValue)
    {
        for(var i in pObjectArray) {
            if (pObjectArray[i][pIdentifier] == pIdentifierValue) {
                return pObjectArray[i][pTargetKey];
            }
        }
        return false;
    }
	/**
	 * Runs through all objects of an object array, searches for a record with specific identity
	 * and deletes it.
	 *
	 * Return Values:
	 * 		true 	if the record was deleted successfully
	 * 		false	if the record was not found
	 *
	 * Autor: Eduard Fekete
	 *
	 * @param pObjectArray			Array of objects
	 * @param pIdentifier			Identifier Key of the object
	 * @param pIdentifierValue		Searched Identifier Value
	 * @returns {boolean}
	 */
	this.deleteObject = function(pObjectArray, pIdentifier, pIdentifierValue)
	{
		for (var i in pObjectArray) {
			for (var key in pObjectArray[i]) {
				if (key == pIdentifier) {
					if (pIdentifierValue == pObjectArray[i][key]) {
						if (i > -1) {
							pObjectArray.splice(i, 1);
							return true;
						}
					}
				}
			}
		}
		return false;
	},
	/**
	 *  Print every object of the object array and show it on the element with ID pOutputID
	 */
	this.showObjects = function outputArray(pObjectArray, pOutputID)
    {
        var output = "";

        for(var i in pObjectArray) {
            output += "<ul>";
            for (var key in pObjectArray[i]) {
                output += "<li>" + key + ": " + pObjectArray[i][key] + "</li>";
            }
            output += "</ul>";
        }

        output += "<hr>";

        $("#"+pOutputID).html(output);
    }
}
.blinkDivs {
  background-color: white;
  border: 3px solid black;
  border-radius: 40px;
  height: 50px;
  width: 50px;
  margin-bottom: 1px;
}

.blinkDivs:hover {
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div_01" class="blinkDivs"></div>
<div id="div_02" class="blinkDivs"></div>
<div id="div_03" class="blinkDivs"></div>

首先仅单击一个圆圈,您会发现它闪烁了 2 秒然后停止。然后单击所有圆圈,您会发现其他间隔被中断并停止闪烁。

最佳答案

$jqElement = $("#"+ self.id); 将 $jqElement 公开到全局范围 (window.$jqElement)。这就是为什么每次调用 blink 时,它都会用一个新元素替换 $jqElement。

将 $jqElement 放在 self 中(或者简单地将 var/let 放在它前面):

function Task(ElementID)
{
    var self = this;
    self.id = ElementID;
    self.interval = null;
    self.limiter = 0;
    self.toggle = 0;
    self.$jqElement = $("#" + self.id);
    self.blink = function()
    {
        self.limiter = 0;
        self.interval = setInterval(function() {

            if (self.toggle == 0) {
                self.$jqElement.css("background-color", "blue");
                self.toggle = 1;
            } else {
                self.$jqElement.css("background-color", "white");
                self.toggle = 0;
            }

            if (self.limiter > 4) {

                OAHelper.deleteObject(taskList, "id", self.id);
                clearInterval(self.interval);
            }
            self.limiter++;
        }, 400);
    }
}

https://jsfiddle.net/g128aunr/1/

使用工厂,Task变成createTask

//Call var task = createTask(elId); instead of new Task();
var createTask = function createTask(elementId) {
    var self = {
        id: elementId
      , interval: 0
      , limiter: 0
      , toggle: 0
      , $element: $jqElement = $("#" + elementId)
      , blink: function blink() {
            self.limiter = 0;
          self.interval = setInterval(function() {
                            if (self.toggle == 0) {
                self.$element.css("background-color", "blue");
                self.toggle = 1;
                } else {
                self.$element.css("background-color", "white");
                self.toggle = 0;
                }

            if (self.limiter > 4) {
                clearInterval(self.interval);
            }
            self.limiter++;
          }, 400);
        }
    };
    return self;
}

关于JavaScript - 让多个元素异步闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44201745/

相关文章:

javascript - 单击时交换多张图像,但一次交换一张

python - 使用函数作为基础对象构造函数的继承

javascript - 不是函数?

javascript - AD FS 2.0 身份验证和 AJAX

javascript - 阻止 Google Maps iframe 捕获鼠标的滚轮行为

javascript - d3.conventions 不是 script.js 中的函数

PHP OOP 类设计

javascript - React/Redux 开发应该是面向对象编程还是函数式编程?

javascript - 在 requirejs 中设置具有循环依赖的 Backbone 集合模型

javascript - 无效的字符串长度错误