Getting div id values from a string and manipulating it

雨燕双飞 提交于 2019-12-25 04:39:19

问题


How do I 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?

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 #.



来源:https://stackoverflow.com/questions/4448924/getting-div-id-values-from-a-string-and-manipulating-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!