Javascript / Jquery用不同的数字来获取ID

时间:2016-09-08 21:06:50

标签: javascript jquery

所以我要改变属性

$('#ctl00_ContentPlaceHolder1_ctl14_ucCal_hlRss').attr({
 title: "Subscribe via RSS"
});
$('#ctl00_ContentPlaceHolder1_ctl14_ucCal_hlRss img').attr({
 title: "Subscribe via RSS",
 alt: "Subscribe via RSS"
});

它运作良好,但我需要将其添加到多个不同的网站,其中" ctl14"将改变(例如在另一个网站上它将是" ctl60")。有没有办法可以修改它以确保它在" ctl ##"之后选择任何数字。然后继续_ucCal_hlRss和_ucCal_hlRss img?

2 个答案:

答案 0 :(得分:4)

$('[id^=ctl00_ContentPlaceHolder1_ctl][id$=_ucCal_hlRss]') 

尝试使用此选择器,它将获取ID为ctl00_ContentPlaceHolder1_ctl并以_ucCal_hlRss结尾的所有元素。

答案 1 :(得分:0)



//function way

function subscribe_title(n) {
    $('#ctl00_ContentPlaceHolder1_ctl' + n + '_ucCal_hlRss').attr({
      title: "Subscribe via RSS"
    }).children('img').attr({
      title: "Subscribe via RSS",
      alt: "Subscribe via RSS"
    });
  } // end function;

//loop method, change the 30 to whatever number you have;
for (var i = 0; i < 30; i++) {
  $('#ctl00_ContentPlaceHolder1_ctl' + i + '_ucCal_hlRss').attr({
    title: "Subscribe via RSS"
  }).children('img').attr({
    title: "Subscribe via RSS",
    alt: "Subscribe via RSS"
  });
} // end for loop;

//using a pre-fetched array of numbers;
var nums = [100, 50, 16, 2];
for (var i = 0; i < nums.length; i++) {
  $('#ctl00_ContentPlaceHolder1_ctl' + nums[i] + '_ucCal_hlRss').attr({
    title: "Subscribe via RSS"
  }).children('img').attr({
    title: "Subscribe via RSS",
    alt: "Subscribe via RSS"
  });
}

//perhaps the easiest way

$('div[id^=ctl00_ContentPlaceHolder1_ctl').attr({
  title: "Subscribe via RSS"
}).children('img').attr({
  title: "Subscribe via RSS",
  alt: "Subscribe via RSS"
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ctl00_ContentPlaceHolder1_ctl10_ucCal_hlRss">
  100
  <img src="//placekitten.com/300x300/" />
</div>
<div id="ctl00_ContentPlaceHolder1_ctl12_ucCal_hlRss">
  100
  <img src="//placekitten.com/300x300/" />
</div>
<div id="ctl00_ContentPlaceHolder1_ctl12_ucCal_hlRss">
  100
  <img src="//placekitten.com/300x300/" />
</div>
&#13;
&#13;
&#13;