Getting div id values from a string and manupulati

2019-09-17 08:31发布

问题:

Can anybody share any idea on how to implement this. I have a variable with comma separated div names. After an AJAX request i have to hide all the divs parsed from the string. So how do i parse the string to get individual div name and hide it ??

Thanks in advance

jQuery code

var dragExternal = 'div1a,div1b,div2a,div2b';

    $.ajax({
    type: 'POST',
    url: "index.html",
    data: dragExternal,
    processData: false,
    success: function(data) {
    alert("Success");
        //Start of code to hide all the div's parsed from the string
         $('#div1a').slideUp(90);
    },
    error: function(data) {
    alert("Cannot Reach Server");
    }
    });

HTML Code

<div id="div1a">Item 1</div>
<div id="div1b">Item 2</div>
<div id="div2a">Item 3</div>
<div id="div2b">Item 4</div>
<div id="div3a">Item 5</div>
<div id="div3b">Item 6</div>

回答1:

Firstly, you'd have to get all the IDs from dragExternal. Do this by using string.split(',').

Then you can use the jQuery.each method to go through each of the items.

var dragExternal = 'div1a,div1b,div2a,div2b';

$.each(dragExternal.split(','), function(i,item){
   $("#" + item).hide();
}); 

Example: http://jsfiddle.net/jonathon/UMCrC/

Although you don't even need $.each (it's nice to know the usage though) - since they're all just strings:

var dragExternal = 'div1a,div1b,div2a,div2b',
    items = dragExternal.split(',')

for(var i=0;i<items.length;i++){
   $("#" + item[i]).hide();
}; 

You use the id selector to get each div by prefixing the div name with #.