如何简化 jQuery 代码以突出显示区域和链接

How to simplify jQuery code to highlight areas and links

本文关键字:显示 区域 链接 何简化 jQuery 代码      更新时间:2023-09-26

我想关联突出显示的区域和链接: square1 - linkone ; square2 - linktwo ; square3 - linkthree ;...

以下代码有效,但繁琐且容易出错;有没有办法为许多区域和链接简化它?

jQuery

$(function() {
  $('.map').maphilight();
  $('#linkone').mouseover(function() {
    $('#square1').mouseover();
  }).mouseout(function() {
    $('#square1').mouseout();
  });
  $("#square1").on({
    mouseover:function(){
      $("#linkone").css("color","red");},
    mouseout:function() {
      $('#linkone').css("color","green");
    }
  });
  $('#linktwo').mouseover(function() {
    $('#square2').mouseover();
  }).mouseout(function() {
    $('#square2').mouseout(); 
  });
  $("#square2").on({
    mouseover:function(){
      $("#linktwo").css("color","red");},
    mouseout:function() {
      $('#linktwo').css("color","green");
    }
  });
  $('#linkthree').mouseover(function() {
    $('#square3').mouseover();
  }).mouseout(function() {
    $('#square3').mouseout(); 
  });
  $("#square3").on({
    mouseover:function(){
      $("#linkthree").css("color","red");},
    mouseout:function() {
      $('#linkthree').css("color","green");
    }
  });
  $('#linkfour').mouseover(function() {
    $('#square4').mouseover();
  }).mouseout(function() {
    $('#square4').mouseout(); 
  });
  $("#square4").on({
    mouseover:function(){
      $("#linkfour").css("color","red");},
    mouseout:function() {
      $('#linkfour').css("color","green");
    }
  });
});

您可以使用 jQuery 查找具有包含指定字符串的 ID 的所有元素

$("[id*='link']")

或者,您可以给出要对类执行相同操作的所有元素,然后按类查找元素

$(".colorgreen").css("color,"green")

在文档 api.jquery.com/category/selectors 中阅读有关选择器的更多信息