图像src在hover上不会改变 - jQuery

时间:2017-04-20 08:15:26

标签: jquery html

我有一个<h1>更改了点击次数以及谁获得了新内容。新内容是两个<span>,ID不同,每个内容都有文字和img。

如果<span>处于悬停状态,我想更改其图像的src。

实际上,我的代码只有在设置$('h1').hover(function() {};时才有效,在我的情况下应该是两个函数,否则会改变两个图像的src。

我尝试$('#SpanId').hover(function() {};但没有成功。

这是我的简化代码:

HTML

<h1>Hello World</h1>
<button>Change title</button>

的jQuery

// On click, change title
$('button').click(function() {
  $('h1').html('');
  $('h1').append('<span id="info">Information <img alt="Info icon" src="http://www.iconsdb.com/icons/preview/orange/info-xxl.png"></span>');
});

// Change info icon on hover
$('#info').hover(function() {
  $('#info img').attr('src', 'http://www.iconsdb.com/icons/preview/gray/info-2-xxl.png');
}, function() {
  $('#info img').attr('src', 'http://www.iconsdb.com/icons/preview/orange/info-xxl.png');
});

Codepen https://codepen.io/Qasph/pen/vmLwWJ

提前致谢,祝你有愉快的一天!

4 个答案:

答案 0 :(得分:2)

我们认为你动态创建一个新的元素,而jQuery还没有意识到它,这使得它不会在它上面监听事件。

我必须在此提供的解决方案是在给定元素上收听给定事件的整个文档func TablecellRegisternib() { self.Hight_table.register(UINib(nibName: "tableviewcellTableViewCell", bundle: nil), forCellReuseIdentifier: "cell") self.weight_table.register(UINib(nibName: "tableviewcellTableViewCell", bundle: nil), forCellReuseIdentifier: "cell") self.Gender_table.register(UINib(nibName: "tableviewcellTableViewCell", bundle: nil), forCellReuseIdentifier: "cell") self.Weekday_table.register(UINib(nibName: "tableviewcellTableViewCell", bundle: nil), forCellReuseIdentifier: "cell") self.Gym_tableview.register(UINib(nibName: "GymTableCell", bundle: nil), forCellReuseIdentifier: "cell1") self.Sports_tableview.register(UINib(nibName: "SpotsTableCell", bundle: nil), forCellReuseIdentifier: "cell2") self.AdditioanlSports_tableview.register(UINib(nibName: "AdditioanlSpotsTableCell", bundle: nil), forCellReuseIdentifier: "cell3") } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of items in the sample data structure. var count:Int? if tableView == self.weight_table { count = WightUnitArray.count } if tableView == self.Hight_table { count = HightUnitArray.count } if tableView == self.Weekday_table { count = WeekdayArray.count } if tableView == self.Gender_table { count = GenderArray.count } if tableView == self.Sports_tableview { count = SportsArray.count } if tableView == self.AdditionalSports_tableview { count = AdditionalSportsArray.count } return count! } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if tableView == self.weight_table { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! tableviewcellTableViewCell cell.detail_lbl.text=WightUnitArray[indexPath.row] cell.selectionStyle = UITableViewCellSelectionStyle.none; cell.detail_lbl.font = UIFont(name:"Roboto-Regular", size:13) cell.detail_lbl.adjustsFontSizeToFitWidth = true if (selectedIndex == indexPath as NSIndexPath?) { cell.radi_btn.setImage(UIImage(named: "radio_btn_active.png"),for:UIControlState.normal) } else { cell.radi_btn.setImage(UIImage(named: "radio_btn.png"),for:UIControlState.normal) } } if tableView == self.Hight_table { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! tableviewcellTableViewCell cell.detail_lbl.text=HightUnitArray[indexPath.row] cell.selectionStyle = UITableViewCellSelectionStyle.none; cell.detail_lbl.font = UIFont(name:"Roboto-Regular", size:13) cell.detail_lbl.adjustsFontSizeToFitWidth = true if (selectedIndex == indexPath as NSIndexPath?) { cell.radi_btn.setImage(UIImage(named: "radio_btn_active.png"),for:UIControlState.normal) } else { cell.radi_btn.setImage(UIImage(named: "radio_btn.png"),for:UIControlState.normal) } } if tableView == self.Weekday_table { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! tableviewcellTableViewCell cell.detail_lbl.text=WeekdayArray[indexPath.row] cell.selectionStyle = UITableViewCellSelectionStyle.none; cell.detail_lbl.font = UIFont(name:"Roboto-Regular", size:13) cell.detail_lbl.adjustsFontSizeToFitWidth = true if (selectedIndex == indexPath as NSIndexPath?) { cell.radi_btn.setImage(UIImage(named: "radio_btn_active.png"),for:UIControlState.normal) } else { cell.radi_btn.setImage(UIImage(named: "radio_btn.png"),for:UIControlState.normal) } } if tableView == self.Gender_table { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! tableviewcellTableViewCell cell.detail_lbl.text=GenderArray[indexPath.row] cell.selectionStyle = UITableViewCellSelectionStyle.none; cell.detail_lbl.font = UIFont(name:"Roboto-Regular", size:13) cell.detail_lbl.adjustsFontSizeToFitWidth = true if (selectedIndex == indexPath as NSIndexPath?) { cell.radi_btn.setImage(UIImage(named: "radio_btn_active.png"),for:UIControlState.normal) } else { cell.radi_btn.setImage(UIImage(named: "radio_btn.png"),for:UIControlState.normal) } } if tableView == self.Gym_tableview { let cell = tableView.dequeueReusableCell(withIdentifier: "cell1") as! GymTableCell var GymDict = GymtableArray[indexPath.row] cell.sportlbl!.text = GymDict["name"] as? String cell.sportlbl?.adjustsFontSizeToFitWidth = true cell.sportlbl?.font = UIFont(name:"Roboto-Regular", size:13) return cell } if tableView == self.Sports_tableview { let cell = tableView.dequeueReusableCell(withIdentifier: "cell3") as! SportsTableCell var SportsDict = SportsArray[indexPath.row] cell.sportlbl1!.text = SportsDict["name"] as? String cell.sportlbl1?.adjustsFontSizeToFitWidth = true cell.sportlbl1?.font = UIFont(name:"Roboto-Regular", size:13) return cell } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if tableView == self.weight_table { tableView.deselectRow(at: indexPath as IndexPath, animated: true) let row = indexPath.row selectedIndex = indexPath as NSIndexPath? let weightstring = (WightUnitArray[row]) if( weightstring != "Pound") { self.WeightUnitTabletxt.text = "kg" } else{ self.WeightUnitTabletxt.text = "lbs" } self.Weight_View.isHidden = true tableView.reloadData() } if tableView == self.Hight_table { tableView.deselectRow(at: indexPath as IndexPath, animated: true) let row = indexPath.row selectedIndex = indexPath as NSIndexPath? let Hightstr = (HightUnitArray[row]) if( Hightstr != "Feet") { self.HeightUnitTabletxt.text = "m" } else{ self.HeightUnitTabletxt.text = "ft" } self.Hight_view.isHidden = true tableView.reloadData() } if tableView == self.Weekday_table { tableView.deselectRow(at: indexPath as IndexPath, animated: true) let row = indexPath.row selectedIndex = indexPath as NSIndexPath? self.FirstDayofWeek_txt.text = (WeekdayArray[row]) self.FirstdayoftheWeek_view.isHidden = true tableView.reloadData() } if tableView == self.Gender_table { tableView.deselectRow(at: indexPath as IndexPath, animated: true) let row = indexPath.row selectedIndex = indexPath as NSIndexPath? self.gender_txt.text = (GenderArray[row]) self.Genderview.isHidden = true tableView.reloadData() } }

$( document ).on( 'event_name', 'searching_element', callback_function )

尝试自己:https://codepen.io/Qasph/pen/vmLwWJ

除此之外,你可以通过使用CSS获得相同的效果,这比为这些简单的东西编写javascript要好得多。

// On click, change title
$('button').click(
  function() {
  $('h1').html('');
  $('h1').append('<span id="info">Information <img alt="Info icon" src="http://www.iconsdb.com/icons/preview/orange/info-xxl.png"></span>');
  }
);

$( document ).on(
  'mouseover',
  '#info',
  function () {
    var $info = $ ( this );
    var $img = $info.find( 'img' );

    $img.attr(
      'src',       
      'http://www.iconsdb.com/icons/preview/orange/info-2-xxl.png'
    );
  }
);

$( document ).on(
  'mouseout',
  '#info',
  function () {
    var $info = $ ( this );
    var $img = $info.find( 'img' );

    $img.attr(
      'src',
      'http://www.iconsdb.com/icons/preview/orange/info-xxl.png'
    );
  }
);
$('button').click(
  function() {
  $('h1').html('');
  $('h1').append('<span id="info">Information <span class="img_icon"></span></span>');
  }
);
body {
  background-color : dodgerblue;
}

h1 .img_icon {
  width : 20px;
  height : 20px;
  display : inline-block;
  background-image : url( 'http://www.iconsdb.com/icons/preview/orange/info-xxl.png' );
  background-repeat : no-repeat;
  background-size : cover;
  background-position : 50% 50%;
}

h1:hover .img_icon {
  background-image : url( 'http://www.iconsdb.com/icons/preview/orange/info-2-xxl.png' );
}

#info:hover {
  color : white;
}

答案 1 :(得分:1)

hover不会触发因为侦听器正在侦听不存在的对象,所以必须在设置#info后设置侦听器:

&#13;
&#13;
// On click, change title
$('button').click(function() {
  $('#info').unbind('hover'); // prevent duplicating hover event

  $('h1').html('');
  $('h1').append('<span id="info">Information <img alt="Info icon" src="http://www.iconsdb.com/icons/preview/orange/info-xxl.png"></span>');
  
  $('#info').hover(function() { 
    $('#info img').attr('src', 'http://www.iconsdb.com/icons/preview/gray/info-2-xxl.png');
  }, function() {
    $('#info img').attr('src', 'http://www.iconsdb.com/icons/preview/orange/info-xxl.png');
  });
});
&#13;
body {background-color: dodgerblue}
h1 img {width:20px}
#info:hover {color: white}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Hello World</h1>
<button>Change title</button>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

原因是当您创建悬停绑定时,您的#info范围不存在。我建议在{/ 1}}上使用mouseenter / mouseleave:

.on

事件侦听器希望事件冒泡到// On click, change title $('button').click(function() { $('h1').html(''); $('h1').append('<span id="info">Information <img alt="Info icon" src="http://www.iconsdb.com/icons/preview/orange/info-xxl.png"></span>'); }); $('h1').on('mouseenter', '#info', function() { $('#info img').attr('src', 'http://www.iconsdb.com/icons/preview/gray/info-2-xxl.png'); }); $('h1').on('mouseleave', '#info', function() { $('#info img').attr('src', 'http://www.iconsdb.com/icons/preview/orange/info-xxl.png'); }); 元素,这是在创建事件处理程序时实际存在的对象。

答案 3 :(得分:1)

Change 

$('#info').hover(function() { 
    $('#info img').attr('src', 'http://www.iconsdb.com/icons/preview/gray/info-2-xxl.png');
  }, function() {
    $('#info img').attr('src', 'http://www.iconsdb.com/icons/preview/orange/info-xxl.png');
  });

To:

$('h1').on({
    mouseenter: function () {
        $('#info img').attr('src', 'http://www.iconsdb.com/icons/preview/gray/info-2-xxl.png');
    },
    mouseleave: function () {
        $('#info img').attr('src', 'http://www.iconsdb.com/icons/preview/orange/info-xxl.png');
    }
}, '#info');