通过点击它来敲击数组的元素(JS)

时间:2017-09-22 06:43:19

标签: javascript jquery html

我有html,我从js

显示数组

这是代码

   <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

<div id ="container">
    <div id="data"></div>
    <input id="text" type=text/>
    <button id="get" onclick="getValue()">Update</button>
</div>

这里是js代码

  var tasks = ["Task 1", "Task 2"];
$.each(tasks, function(){
    $('#data').append('<li class="clickable">'+this + '</li>');
});

我从列表中获取元素

$(document).on('click', '.clickable', function() {
var str =  $(this);

});

现在我需要通过js攻击它。我怎么能这样做?

4 个答案:

答案 0 :(得分:2)

您可以点击strike元素执行此操作:

&#13;
&#13;
var tasks = ["Task 1", "Task 2"];
$.each(tasks, function(){
    $('#data').append('<li class="clickable">'+this + '</li>');
});
$(document).on('click', '.clickable', function() {
  $(this).css("text-decoration", "line-through");
});
&#13;
   <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

<div id ="container">
    <div id="data"></div>
    <input id="text" type=text/>
    <button id="get" onclick="getValue()">Update</button>
</div>
&#13;
&#13;
&#13;

但是如果你想在每次点击时添加和删除点击,请使用:

&#13;
&#13;
var tasks = ["Task 1", "Task 2"];
$.each(tasks, function(){
    $('#data').append('<li class="clickable">'+this + '</li>');
});
$(document).on('click', '.clickable', function() {
  $(this).toggleClass('strikeClass');
});
&#13;
.strikeClass{
  text-decoration: line-through;
}
&#13;
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

<div id ="container">
    <div id="data"></div>
    <input id="text" type=text/>
    <button id="get" onclick="getValue()">Update</button>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您有两种选择。

1)包裹del标签

$(document).on('click', '.clickable', function() {
     var str =  $(this);
     srt.wrap("<del></del>");
});

2)添加样式属性

$(document).on('click', '.clickable', function() {
     var str =  $(this);
     str.css("text-decoration", "line-through");       
});

答案 2 :(得分:0)

如果您需要删除元素,只需执行onClick="$(this).remove();"

即可

$(document).ready(function() {
  $(document).on('click', '.clickable', function() {
    $(this).remove();
  });

  var tasks = ["Task 1", "Task 2"];

  $.each(tasks, function() {
    $('#data').append('<li class="clickable">' + this + '</li>');
  });
});
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

<div id="container">
  <div id="data"></div>
  <input id="text" type=text/>
  <button id="get" onclick="getValue()">Update</button>
</div>

答案 3 :(得分:-1)

我不明白你的意思

$(document).on('click', '.clickable', function() {
 var txt = this.textContent;
this.innerHTML  = txt.strike();
});