jquery中每个循环中的$(this)和$(“#id”)之间的差异

Difference between $(this) and $("#id") in a each loop in jquery

本文关键字:#id 之间 this 循环 jquery      更新时间:2023-09-26

我是jquery的新手。我知道这个问题很愚蠢,但我遗漏了一些概念。问题是:

$("input.integers").each(function(index) {
    console.log("----");
    console.log($(this).attr('id') + " " + $(this).val()); 
    console.log($(this).attr('id') + " " + $("#"+$(this).attr('id')).val());
    // the next log is here just to show a direct selection. I'm concerned about the two logs above this one 
    console.log($("#myId").attr('id'), $("#myId").val());
    that.setModelData($(this).attr('id'), $(this).val());
});

这是输出:

PhantomJS 1.6 (Linux) LOG: '----'
PhantomJS 1.6 (Linux): Executed 61 of 90
PhantomJS 1.6 (Linux) LOG: 'myId '
PhantomJS 1.6 (Linux): Executed 61 of 90
PhantomJS 1.6 (Linux) LOG: 'myId 123'
PhantomJS 1.6 (Linux): Executed 61 of 90
PhantomJS 1.6 (Linux) LOG: [ 'myId', '123' ]

则输入标签。为什么$(this).val()是空的,而$("#"+$(this).attr('id')).val()包含正确的值?

更新:

因果报应测试:

it('the model must be updated', function(){
    $("#myId").val("123");  
    $("#save-process").click();
    server.respond();
    expect(fdtView.model.get('myId')).toBe("123");
});

固定装置:

<input id="myId" name="myId"
    class="integers" type="text" /> 

在循环中,与$("input.integrates")选择器匹配。所以,jquery在内存中有这个选择器$("#myId")是一个唯一的选择器,对于每个循环,jquery都会搜索并分析这个元素。这只是巧合,因为你的html代码是:

<input class="integers" id="myId" />

然而,如果您有许多输入具有相同的CSS类,这个将不同。

具有多个输入的示例。

HTML代码:

<input class="integers" value="toto"/>
<input class="integers" value="titi"/>
<input class="integers" value="tata"/>
<input class="integers" value="tutu"/>

JS代码:

$("input.integers").each(function(index) {
console.log("Value = "+$(this).val);
}

控制台日志:

Value = toto
Value = titi
Value = tata
Value = tutu

因此,要回答您的问题,如果this.val()$("#"+$(this).attr('id')).val())不同,则加载它的选择器不好。

好吧,我不得不说这是因果报应的问题,而不是jquery的问题。

我们使用Backbone.js,视图正在加载视图定义中的模板:

template : _.template($("#mytemplate").html()),

Karma在加载测试时,如果没有找到fixture,就会出现异常,所以我们在一个名为fixtures.js的文件中添加了启动时的fixture:

loadFixtures('viewtemplate.html','mytemplate.html');

(@Blame)有人在jasmine测试套件的beforeEach中添加了以下代码:

beforeEach( function() {
    loadFixtures('currentStepContainerFixture.html', 'mytemplate.html');

因此,固定装置加载了两次

当我在我的代码中使用时:

 console.log($(this).attr('id') + " " + $(this).val()); 
 console.log($(this).attr('id') + " " + $("#"+$(this).attr('id')).val());

基本上,第一个日志是关于当前元素的,而第二个日志则是关于具有该id的第一个输入。

这就是为什么我们会有这种掉队的行为。我不得不说,如果存在两个id相同的元素,则抛出某种异常会很有帮助

PhantomJS 1.6 (Linux): Executed 61 of 90
PhantomJS 1.6 (Linux) LOG: 'myId ' --> current $(this)
PhantomJS 1.6 (Linux): Executed 61 of 90
PhantomJS 1.6 (Linux) LOG: 'myId 123' --> first occurrence of "#myId"

我不配得到这四分,问题出在显示器和键盘之间。对不起:(