Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

javascript - jQuery Find Closest Input

I have structure like each image has input below. I have x images on the screen. Each of image has onlick option

onclick="imageClicked(this)"

Function creates border to image and show collapsed input. Image`s border is showing but input is not beign visible.

Here`s the function

function imageClicked(image) {
    var input = $(image).closest("input");
    $(image).css('outline', "solid 2px #5bc0de");
    $(input).css("visibility", "visible");
    $(input).focus();

    $(input).focusout(function () {
        $(image).css('outline', "0");
        if ($(input).val() === "0") {
            $(input).css("visibility", "collapse");
        }
    });
    $(image).focusout(function () {
        if ($(input).val() === "") {
            $(image).css('outline', "0");
        }
    });
}

Here is HTML Structure in Razor View

@for (int i = 0; i < Model.Boxes.Count; i++){
    var base64 = Convert.ToBase64String(Model.Boxes[i].Photo);
    var imgSrc = String.Format("data:image/gif;base64,{0}", base64);

    var imageId = Model.Boxes[i].BoxId;
    @Html.HiddenFor(m => m.Boxes[i].BoxId)    
    <div class="col-md-2">
        <img src="@imgSrc" width="50%" alt="@Model.Boxes[i].Name" id="@string.Format("image{0}", imageId)" onclick="imageClicked(this)" />
        @Html.TextBoxFor(m => m.Boxes[i].Quantity, new { @class = "form-control", @style = "visibility: collapse; width: 50%; margin-top: 1%", @id = string.Format("input{0}", imageId) })
    </div>
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Closest will search for the parent elements. Here the input is not the parent element of the image. Its a sibling only. You can use siblings() selector for this purpose.

var input = $(image).siblings("input");

Or you can use,

var input = $(image).closest(".col-md-2").find("input");
  • Get the parent div(since the image and input are under same parent)
  • Then find the child input of that parent

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...