简体   繁体   中英

jQuery $(this) on child selectors?

Building a similar setup to Twitters Follow/Unfollow button and can't quite get it working with jQuery.

Complete so far; - jQuery on a single known ID for a <button> for updating all the details needed - API powering the server side logic - Everything else server side is working perfectly

Can't figure out; - How to expand the functionality I have for a single known ID to multiple unknown IDs .

Here's the code I have working for the known single point;

//Update Links
                            $("#api-follow-button").html(buttonText);
                            $("#api-follow-button").attr("currentState", currentState);

The above code is wrapped in a function with a whole host of other code which is triggered by;

$(document).on("click", "#api-follow-button", followButton());

This works perfect as I know the ID. The challenge being, how to expand this when the ID that is to be updated is unknown?

I've tested so many variations using $(this) and I'm not getting anything working. I'm sure I'm just missing something blindingly obvious here.

So imagine this code as an example;

<button id="button-idxxx">Text 1</button>
<button id="button-idxxx">Text 2</button>
<button id="button-idxxx">Text 3</button>

Then whenever someone clicks on one of the <button> , then the 'Text X' would change to something else

Ideas?

This $(this) you mention probably works correct ( although you did not post your relevant code ).

The error seems to be in $(document).on("click", "#api-follow-button", followButton()); where the () should be missing from the followButton method.

So try with

$(document).on('click', '[id^="button-id"]', followButton);

( the [id^="button-id"] selector matches elements with an id attribute that starts with button-id text )

Your followButton should be something like this

function followButton(e){
    e.preventDefault();
    // define buttonText and currentState here 
    // unless they come from elsewhere
    $(this)
        .html(buttonText)
        .attr("currentState", currentState);
}

(Thinking out loud) You could potentially use the Attribute Starts With Selector found in the linked article. With this selector, you can select all the buttons that may contain a specific prefix (ie button-id ) from your example without knowing the entire id of the element.

From the attribute starts-with selector docs:

Description : Selects elements that have the specified attribute with a value beginning exactly with a given string.

For example:

 jQuery(function ($) { $(document).on('click', '[id^="button-id"]', function () { alert($(this).text()); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button type="button" id="button-id12345"> Text 1 </button> <button type="button" id="button-id678910"> Text 2 </button> <button type="button" id="button-id1112131415"> Text 3 </button> 

Thanks all. The code in the fiddle for alert($(this).text()); works perfectly but when doing anything like updating the text on the page this didn't seem to work for some reason. With a bit of fiddling around based on the helpful info here's what I came up with which worked;

HTML Buttons

<button type="button" class="btn btn-lg btn-success" id="api-follow-button-uniqueID-xxx" currentState="NotFollowing">
<button type="button" class="btn btn-lg btn-success" id="api-follow-button-uniqueID-xxx" currentState="NotFollowing">
<button type="button" class="btn btn-lg btn-success" id="api-follow-button-uniqueID-xxx" currentState="NotFollowing">

jQuery Code

$(document).ready(function () {
                $(document).on('click', '[id^="api-follow-button"]', function followButton(e) {

                    e.preventDefault();

                    var currentState = $(this).attr("currentState");

//This line below ensures that you can then use the ID selector to update the relevant part of the HTML as needed, see note below
                    var buttonID = $(this).attr("id");


                            var buttonText = "";
                            var currentState = "";

                                buttonText = "Unfollow";
                                currentState = "Following";

                            //Update Links
//This part from comment above
                            $("button[id=" + buttonID + "]")
                                    .html(buttonText)
                                    .attr("currentState", currentState);

                        });
                    }

                });
            });

Looks like it's all done what is needed now. I've removed a bunch of code from above to simplify things

Thanks all

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM