Dynamic selection example using variables in Jquery selector

  • 2020-03-30 03:35:50
  • OfStack

Example 1:


<table>
  <tr>
    <th> The user name </th>
    <th> state </th>
  <tr>
  <tr>
    <td> Zhang SAN </td>
    <td data-uid="10000"> normal </td>
  <tr>
  <tr>
    <td> Li si </td>
    <td data-uid="10001"> freeze </td>
  <tr>
  <tr>
    <td> Two pock </td>
    <td data-uid=10002> freeze </td>
  <tr>
</table>

<script type="text/javascript">
$(document).ready(function(){
  var uid = 1001;
  $("td[data-uid = "+ uid +"]").html(' normal ');
}
</script>

Example 2:


<script type="text/javascript">
 $(function(){
  alert(123);
  var v=4;
  var test=$("input[type='radio'][value='"+v+"']");//Just concatenate the string directly
  console.info(test);
  var testValue=test.attr({"checked":true});
  console.info(testValue);
 }); 
 </script>
 
 <body>
  This is my JSP page. <br>
  <table>
 <tr>
 <td> Gender: </td>
 <td>
  <input name="sex" type="radio" value="0"/> male  0
  <input name="sex" type="radio" value="1"/> female  1
  <input name="sex" type="radio" value="2"/> female  2
  <input name="sex" type="radio" value="3"/> female  3
  <input name="sex" type="radio" value="4"/> female  4
 </td>
 </tr>
  </table>
 </body>

Example 3. Problems that should be paid attention to when using variables for selector parameters in jQuery

This is the original code


var li_index = $(this).index();

var $content_index = li_index + 2;

var $content_progress = $( " div.content:eq( "  + $content_index +  " ) " );

var $newavalue = $(this).find( " a " ).attr( " name " );

var $resource = $(this).find( " a " ).html().replace( "Home page" ,$newavalue);

var $afterresource = $resource.replace($newavalue, "" );

var $afterresource = $newavalue + $afterresource.replace( "Home page" ,$newavalue);

The implementation is keyword replacement, but by the third line does not perform, debugging, replacement, ah, do not work. I've been asking questions in various groups since the morning, and finally... Lomu of our home base sees blood for a while:

You're not writing it right

To connect descriptor


$( " div.content:nth-child($content_index) " );

Instead of


$( " div.content:nth-child( "  + $content_index +  " ) " );

The point is that there are quotes on the outside

Some quotes are treated as strings

It really feels like something fundamental is wrong, and you can't find the problem by debugging it yourself. Like the + sign, which I haven't seen in my books. Appear this kind of error baidu also does not know what keyword. I don't know   The + sign is also used for variables in the selector, and the sharp jQuery doesn't explicitly say that the + sign is used for variables in the selector, including our w3cschool.


Related articles: