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

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')保存成一个变量以外,请问还有地方需要优化?把匿名函数搬出来有意义吗?

阅读 4.4k
3 个回答

$("#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);

第二个题,你可以把a标签保存为一个外部变量,并且在for循环的时候,直接var 声明i和a.length。绑定的方法你可以用事件监听同时绑定两个函数的方式试试

第一题
因为jQuery自己有find方法 所以用循环还是多余了
我的html结构:(大概看一下)

clipboard.png

代码:

$("table tr").find("td[class='checked']").val()

以上完全可以获取到 然后再将值给value就可以了@_@
所以这一句就很简单了

至于第二题 个人认为楼上几位已经说得很清楚了
addEventLister事件监听直接监听两个事件

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题