Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript JQuery仅影响”的;这";同类元素_Javascript_Jquery_Html - Fatal编程技术网

Javascript JQuery仅影响”的;这";同类元素

Javascript JQuery仅影响”的;这";同类元素,javascript,jquery,html,Javascript,Jquery,Html,我有一堆具有相同类的html元素和一个JQueryclick函数当我单击其中一个元素时,同一类的所有元素都会受到该函数的影响 我的问题是:如何修改以下代码,以便只影响单击的元素而不是同一类的所有元素 jquery $('.editorTile').click(function(event){ $(this).data('type', selectedTile); $(this).data('imgx', selectedTile_imgX); $(this).

我有一堆具有相同类的html元素和一个JQuery
click
函数当我单击其中一个元素时,同一类的所有元素都会受到该函数的影响

我的问题是:如何修改以下代码,以便只影响单击的元素而不是同一类的所有元素

jquery

$('.editorTile').click(function(event){
      $(this).data('type', selectedTile);
      $(this).data('imgx', selectedTile_imgX);
      $(this).data('imgy', selectedTile_imgY);          
});
html


//只影响这一点
//或者这个。。。

它已经可以按照您现有的方式工作了,但不会很明显。在本演示中,单击每一行

指向函数的所有者,在本例中,该函数是碰巧被单击的特定元素。一个更为技术性的术语,用来表示被点击、悬停等的元素,被称为“事件的起源”。您还可以使用
event.target
属性,该属性(与
this
类似,但不太容易混淆)指向“事件的起源”。演示中的第二个示例演示了
event.target
的使用

演示
$('.a')。单击(函数(事件){
$(this.css('background','red');
});
$('.b')。在('click',函数(e)上{
$(e.target).css('font-size','36px');
});

这
是一个
关键词
它起作用了!
事件目标
是一个
财产
事件对象的属性

必须生成动态类或id才能将特定的div作为选择器

解决这个问题的另一种方法是使用:eq(n)和选择器,如果您知道必须调用click的div

例如,在您的案例中:-

<div class="level">
<div class="a editorTile" ...>
<div class="a editorTile" ...> // affect only this
<div class="a editorTile" ...>
<div class="a editorTile" ...> // or this...

为此,您必须已经知道确切的div顺序,这里有一个简单易行的解决方案:

<div class="level">
   <div class="a editorTile">h</div>
   <div class="a editorTile">g</div>
   <div class="a editorTile">g</div>
   <div class="a editorTile">g</div>
</div>

 $('.editorTile').each(function(){
    $(this).click(function(){
     $(this).text("I am clicked");
   });
 });

H
G
G
G
$('.editorile')。每个(函数(){
$(此)。单击(函数(){
$(此).text(“我被点击”);
});
});

或者您需要其他内容,以便您可以询问。

$(此)
->
$(event.target)
使用
,只有当前单击的元素应该更改。您的代码有错误吗?单击console.log()时看起来是正常的,当我单击其中一个元素时,相同的消息会重复几次。当然,
单击
适用于所有元素。但是
这个
只意味着一个
元素
。jQuery确实知道没有所有这些特定选择器的确切元素comment@Mamun事实并非如此。这就是这里的奥秘。我不知道为什么OPs代码不能很好地工作,我只是做了同样的操作,它只影响单击的元素,但为什么要对所有元素重复console.log()?还没有回答完问题。
$("div.editorTile:eq(2)") && $("div.editorTile(4)") gives you second and fourth element.
<div class="level">
   <div class="a editorTile">h</div>
   <div class="a editorTile">g</div>
   <div class="a editorTile">g</div>
   <div class="a editorTile">g</div>
</div>

 $('.editorTile').each(function(){
    $(this).click(function(){
     $(this).text("I am clicked");
   });
 });