jQuery点击功能 /如果语句不起作用



有人可以向我解释为什么这不起作用,需要更改什么?我正在尝试使用3个单击时执行不同动作的图标。

 var array = [
        {val : 1, icon: 'fa-bolt'},
        {val : 2, icon: 'fa-exclamation'},
        {val : 3, icon: 'fa-undo-alt'}
    ];

$(array).each(function() {
   var $item = $('<i>');
   $item.attr('value', this.val).attr('class', 'fas fa-2x ' + this.icon + ' item-class');
   $body.append($item);
});

$('.item-class').on('click', function(){
    if ($(this).val() === '1') {
      //do stuff
    }
    if ($(this).val() === '2') {
      //do stuff
    }
    if ($(this).val() === '3') {
      //do stuff
    }
});

您的问题在此行中:

$('.item-class').on('click', function(){

SVG Elements 由Fontawesome创建。您需要将点击事件处理程序委托:

$body.on('click', '.item-class', function (e) {

第二个神秘作品是在这一行中:

$(this).val()

现在值是SVG元素的属性。

将其更改为:

$(this).attr('value')

var $body = $('body');
var array = [
    {val: 1, icon: 'fa-bolt'},
    {val: 2, icon: 'fa-exclamation'},
    {val: 3, icon: 'fa-undo-alt'}
];
$(array).each(function () {
    var $item = $('<i/>');
    $item.attr('value', this.val).attr('class', 'fas fa-2x ' + this.icon + ' item-class');
    $body.append($item);
});
$body.on('click', '.item-class', function (e) {
    var clickedValue = $(this).attr('value');
    console.log(clickedValue);
    if (clickedValue === '1') {
        //do stuff
    }
    if (clickedValue === '2') {
        //do stuff
    }
    if (clickedValue === '3') {
        //do stuff
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>

您可以添加onClick属性,类似的内容:

$(array).each(function() {
  var $item = $('<i>');
  $item
    .attr('value', this.val)
    .attr('class', 'fas fa-2x ' + this.icon + ' item-class')
    .attr('onClick', 'show('+this.val+')');
  $('body').append($item);
});
function show(value) {
  console.log(value)
}

为什么要为 i 元素使用值属性?这不符合HTML。

您可以使用数据 - *属性:

$item.data('value', this.val).attr('class', 'fas fa-2x ' + this.icon + ' item-class');

和在您的循环中:

// it will return int type, don't test with string
if ($(this).data('value') === 1) {

$(this(.val((仅用于输入,在这里您只需在HTML元素上添加 value 属性。

最新更新