使用带有多个按钮的“this”

时间:2018-03-02 04:08:50

标签: javascript jquery css

我不确定如何用这个来搜索,看看我的问题是否已经得到解答。

有没有办法让我使用“this”将这两个陈述合并为一个?

$("#rock1").click(function (event){
    $("#rock").css("background-image","url("+rock1.image+")")
    $('#flavorText').text(rock1.text);


});

$("#rock2").click(function (event){
    $("#rock").css("background-image","url("+rock2.image+")")
    $('#flavorText').text(rock2.text);



});

当我尝试使用“this.image”时,我遇到了将图像复制到我不想要的地方以及其他图像消失的问题。

编辑:这是其他相关代码。

HTML

<div class="weapon rock1"  id="rock">


</div>

 <select>
    <option value="0" id="rock1"> Rock
    </option>
    <option class="hide" value="1" id="rock2"> Pet Rock
    </option>
 </select>

    var rock1 = {
type: "Beginner Rock",
text:"A rock.",
image: "https://drive.google.com/uc?export=view&id=17i_dEIACd9TxrPEE13-jmzUrwpX5hsLt"

};

1 个答案:

答案 0 :(得分:1)

这是如何完成的示例。 event处理程序可以通过将它们放在逗号(,)分隔的字符串中添加到多个选择器中。

使用event.target.id获取点击按钮的id

&#13;
&#13;
var dataObj = {
  rock1: {
    image: "https://www.birdlife.org/sites/default/files/styles/1600/public/bialowieza_forest_c_tomasz_wilk_0.jpg?itok=iXRoJtoL",
    text: "Forest1"
  },
  rock2: {
    image: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQudl_IoPOvhxPMaFRVl3UdBMuZ4MK63FF0Y4e1X7SYBGT2-rSnTQ",
    text: "Forest2"
  }
}

$("#rock1,#rock2").click(function(event) {
  var target = event.target.id;
  $("#rock").css("background-image", "url(" + dataObj[target].image + ")")
  $('#flavorText').text(dataObj[target].text);
});
&#13;
#rock {
  width: 200px;
  height: 200px;
  display: inline-block;
  border: 1px solid green;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="rock1">Rock 1</button>
<button id="rock2">Rock 2</button>


<div id="rock"></div>
<div id="flavorText">
  <div>
&#13;
&#13;
&#13;

或者,您也可以将this.id传递给内联事件处理程序

中的函数

&#13;
&#13;
var dataObj = {
  rock1: {
    image: "https://www.birdlife.org/sites/default/files/styles/1600/public/bialowieza_forest_c_tomasz_wilk_0.jpg?itok=iXRoJtoL",
    text: "Forest1"
  },
  rock2: {
    image: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQudl_IoPOvhxPMaFRVl3UdBMuZ4MK63FF0Y4e1X7SYBGT2-rSnTQ",
    text: "Forest2"
  }
}

function updateDisp(id) {
  $("#rock").css("background-image", "url(" + dataObj[id].image + ")")
  $('#flavorText').text(dataObj[id].text);

}
&#13;
#rock {
  width: 200px;
  height: 200px;
  display: inline-block;
  border: 1px solid green;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="rock1" onclick="updateDisp(this.id)">Rock 1</button>
<button id="rock2" onclick="updateDisp(this.id)">Rock 2</button>


<div id="rock"></div>
<div id="flavorText">
  <div>
&#13;
&#13;
&#13;