第二次单击时不会删除jQuery Array

时间:2016-03-30 06:28:30

标签: javascript jquery arrays

DEMO

您好,

点击图片我正在将图片名称(属性)传递给数组,工作正常,但每当用户再次点击取消选择时,我正试图删除当前名称($(这个) )),它没有发生,而是被完全删除(空数组)。 并且每次逗号都附加第一个元素:-(

JS : 
 questionCount = 0;
        $('.q2 .product-multiple').on('click',function(e){
            if($(this).hasClass('selectTag')){
                questionCount--;
                $(this).removeClass('selectTag');

                removeItem = "Removing Clicked element Name -  " + $(this).find('img').attr('name')
                alert(removeItem);
            console.log("Should be Removed here.. " +" "+ getTagsNameArray)


            } 
            else {
                questionCount++;
                $(this).addClass('selectTag');
                getTagsNameArray = new Array();
                getTagsName = getTagsName + "," + $(this).find('img').attr('name');
                getTagsNameArray.push(getTagsName)
        console.log("Passing Value in Array - " +" "+ getTagsNameArray)

            }
            });

        $('.q2-get-answer').on('click', function(){
            getTagsName = getTagsName +" / "+ $('.q2-answer').find('.product-multiple.selectTag img').attr('name');
            alert(getTagsName)
            console.log(getTagsName);
        })


html : 
<div class="q2">
            <label for="q2">What type of symptoms that your child has?</label>
            <div class="q2-answer" id="q2">
                <div class="product-multiple">
                    <img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="gassy">
                    <div>Gassy</div>
                </div>
                <div class="product-multiple">
                    <img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="fussy">
                    <div>Fussy</div>
                </div>
                <div class="product-multiple">
                    <img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="diahrea">
                    <div>Diahrea</div>
                </div>
                <div class="product-multiple">
                    <img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="spitup">
                    <div>Spit Up</div>
                </div>
                <div class="product-multiple">
                    <img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="constipation">
                    <div>Constipation</div>
                </div>
            </div>
            <div class="q2-get-answer">
                Q3 click me
            </div>
        </div>

谢谢你的回答!!

我可以为此创建一个通用函数,因为有许多相同功能的问题吗? 有什么想法吗 ?

再次感谢

6 个答案:

答案 0 :(得分:2)

试试这个。

PasswordAuthentication

答案 1 :(得分:2)

您需要在函数外声明数组。您使用,将数组推送到数组中,这是不需要的。您的JS代码如下所示:

var getQ1Answer, getQ2Answer, getQ3Answer, getQ4Answer, getQ5Answer, getQ6Answer, sliderValue, selectMonth, q1answer, getTags;
var getTagsName = "";
var getTagsNameArray = new Array();     // here you should create an array
questionCount = 0;
$('.q2 .product-multiple').on('click',function(e){
    if($(this).hasClass('selectTag')){
        questionCount--;
        $(this).removeClass('selectTag');
        removeItem = "Removing Clicked element Name -  " + $(this).find('img').attr('name')
        alert(removeItem);
        var doubleSelect = $(this).find('img').attr('name');
        var index = getTagsNameArray.indexOf(doubleSelect);
        console.log(index)
        if (index > -1) {
            getTagsNameArray.splice(index, 1);
        }
        console.log("Should be Removed here.. " +" "+ getTagsNameArray)
    } 
    else {
        questionCount++;
        $(this).addClass('selectTag');
        getTagsNameArray.push($(this).find('img').attr('name'));            //change is here
        console.log("Passing Value in Array - " +" "+ getTagsNameArray)
    }
});

$('.q2-get-answer').on('click', function(){
    getTagsName = getTagsName +" / "+ $('.q2-answer').find('.product-multiple.selectTag img').attr('name');
    alert(getTagsName)
    console.log(getTagsName);
})

Fiddle

答案 2 :(得分:1)

您将一个字符串附加到一个数组,该数组将数组转换为字符串:getTagsName +&#34;,&#34; 您需要使用getTagName.push($(this).find(&#39; img&#39;)。attr(&#39; name&#)将新元素添加到数组中,而不是将字符串附加到数组中。 39))。您可以使用indexOf()和splice()删除项目。 如果要打印数组,只需使用getTagsName.join()。这将使您的数组以逗号分隔的字符串形式转换。

答案 3 :(得分:1)

  

首先,你不应该有这么多变数。只是push / splicefrom/to数组的变量。

Array.prototype.splice() =&gt; splice()方法通过删除现有元素和/或添加新元素来更改数组的内容。

语法: array.splice(start, deleteCount[, item1[, item2[, ...]]])

var getTagsNameArray = [];
$('.q2 .product-multiple').on('click', function(e) {
  var item = $(this).find('img').attr('name');
  if ($(this).hasClass('selectTag')) {
    $(this).removeClass('selectTag');
    getTagsNameArray.splice(getTagsNameArray.indexOf(item), 1);
  } else {
    $(this).addClass('selectTag');
    getTagsNameArray.push(item);
  }
  console.log(getTagsNameArray.join(', '));
});

$('.q2-get-answer').on('click', function() {
  console.log(getTagsNameArray.join(', '));
})
.product-multiple {
  float: left;
  margin: 10px;
}
.product-multiple img {
  width: 200px;
  height: 150px;
}
.product-multiple img:hover {
  cursor: pointer;
}
.ui-state-default,
.ui-widget-content .ui-state-default,
.ui-widget-header .ui-state-default {
  cursor: pointer;
}
.digestive-tool {
  padding: 10px;
  margin: 10px;
  border: 1px solid #ccc;
}
.digestive-tool .q1-answer li,
.digestive-tool .q2-answer li,
.digestive-tool .q3-answer li,
.digestive-tool .q4-answer li,
.digestive-tool .q5-answer li,
.digestive-tool .q6-answer li {
  list-style-type: none;
  display: inline-block;
}
.digestive-tool .q1-get-answer,
.digestive-tool .q2-get-answer,
.digestive-tool .q3-get-answer,
.digestive-tool .q4-get-answer,
.digestive-tool .q5-get-answer,
.digestive-tool .q6-get-answer {
  border: 1px solid #f00;
  padding: 10px;
  display: inline-block;
  cursor: pointer;
}
.digestive-tool .product,
.digestive-tool .product-multiple {
  display: inline-block;
}
.digestive-tool .product img,
.digestive-tool .product-multiple img {
  width: 150px;
  height: 180px;
  cursor: pointer;
}
.selectTag {
  border: 2px solid #00257a;
}
.q2-get-answer {
  margin-top: 20px;
  clear: left;
  border: 1px solid #900;
  background: #f00;
  cursor: pointer;
  width: 200px;
  padding: 20px;
  color: #fff;
}
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="q2">
  <label for="q2">What type of symptoms that your child has?</label>
  <div class="q2-answer" id="q2">
    <div class="product-multiple">
      <img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="gassy">
      <div>Gassy</div>
    </div>
    <div class="product-multiple">
      <img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="fussy">
      <div>Fussy</div>
    </div>
    <div class="product-multiple">
      <img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="diahrea">
      <div>Diahrea</div>
    </div>
    <div class="product-multiple">
      <img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="spitup">
      <div>Spit Up</div>
    </div>
    <div class="product-multiple">
      <img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="constipation">
      <div>Constipation</div>
    </div>
  </div>
  <div class="q2-get-answer">
    Q3 click me
  </div>
</div>

Fiddle here

答案 4 :(得分:1)

这是因为每次取消选择getTagsNameArray时都会创建一个新的$('.q2 .product-multiple')数组。请参阅单击处理程序中的else语句。

如果我正确理解您的问题,您需要一个名为所选图像属性的数组吗?在那种情况下:

  • 在点击处理程序
  • 之外声明并创建getTagsNameArray
  • 点击图片,将名称添加到数组
  • 再次点击(如此取消选择),在数组中找到名称和 删除它。

https://jsfiddle.net/gcke1msx/7/

var getTagsNameArray = [];

$('.q2 .product-multiple').on('click', function(e) {
  // get the name of the image
  var name = $(this).find('img').attr('name');

  if($(this).hasClass('selectTag')) {
    // it was selected, now unselected
    // so remove its name from the array
    // see: http://stackoverflow.com/questions/5767325/remove-a-particular-element-from-an-array-in-javascript
    $(this).removeClass('selectTag');
    var index = getTagsNameArray.indexOf(name);
    getTagsNameArray.splice(index, 1);
  } else {
    // selected it
    // and add name to array
    $(this).addClass('selectTag');
    getTagsNameArray.push(name);
  }
});

$('.q2-get-answer').on('click', function(){
  alert('selected: ' + getTagsNameArray.join(', '));      
})

答案 5 :(得分:0)

这是一个现场演示 https://jsfiddle.net/soonsuweb/4ea54xxu/3/

您可以使用 array.push,splice,join

var selected = [];

$('.q2 .product-multiple').on('click',function (e) {
    if($(this).hasClass('selectTag')){
        $(this).removeClass('selectTag');
        var name = $(this).find('img').attr('name');

        // remove the name from selected
        for (var i=0; i<selected.length; i++) {
            if (name === selected[i]) {
                selected.splice(i, 1);
            }
        }

        console.log("Should be Removed here.. ", name);
        console.log("Passing Value in Array - ", selected.join(', '))
    }
    else {
        $(this).addClass('selectTag');

        var name = $(this).find('img').attr('name');
        selected.push(name);
        console.log("Passing Value in Array - ", selected.join(', '))
    }
});

$('.q2-get-answer').on('click', function () {
    alert(selected.join(', '));
    console.log(selected.join(', '));
});