为了账号安全,请及时绑定邮箱和手机立即绑定

使用jQuery,找到id位selector的select标签中有用data-target属性为

使用jQuery,找到id位selector的select标签中有用data-target属性为

呼唤远方 2018-10-12 14:10:49
var value; $('#selector option').each(function(){    if ($(this).data('target') == 'isme') {         value = $(this).val();     } });去年今日头条的一道前端笔试题,对jQuery不太熟悉,不知道除了这种写法有没有更简单的方式?还有一题,简化以下代码:for (var i = 0; i < document.getElementsByTagName('a').length; i++) {     document.getElementsByTagName('a')[i].onmouseover = function () {        this.style.color = 'red';     }    document.getElementsByTagName('a')[i].onmouseout = function () {        this.style.color = '';     } }除了先把document.getElementsByTagName('a')保存成一个变量以外,请问还有地方需要优化?把匿名函数搬出来有意义吗?
查看完整描述

1 回答

?
侃侃无极

TA贡献2051条经验 获得超10个赞

$("#selector option[data-target=isme]")

  • 既然是循环所有的a,那么不需要用for循环,还多声明了i变量。

  • 感觉,只是感觉,应该把onmouseover, onmouseout提出来声明,避免重复的定义function

  • 里面的东西需要不需要提出来,不知道。。。感觉从性能上不需要,从代码观赏性上来说,需要吧

function onmouseover(){  this.style.color = 'red';
}function onmouseout(){  this.style.color = '';
}function bindMouseEvent(target){
  target.onmouseover = onmouseover;
  target.onmouseout = onmouseout;
}document.querySelectorAll('a').forEach(bindMouseEvent);


查看完整回答
反对 回复 2018-11-08
  • 1 回答
  • 0 关注
  • 1068 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号