开发者

jquery Create Spans and then apply functions to them

开发者 https://www.devze.com 2023-01-06 00:01 出处:网络
I am creating a form in jQuery. When the page loads I\'m hiding all textboxes and trying to replace them with a span.

I am creating a form in jQuery. When the page loads I'm hiding all textboxes and trying to replace them with a span.

$("form input:text").each(function(index) {
    $(this).after("<span id='Span_" + $(this).attr("id") + "'>" + $(this).val() + "</span").hide();
});

This goes through each text input pla开发者_Go百科ces a span after the textbox with a id the same as the textbox but "span_" appened to the start..

Now I want to apply hover on the spans: $("span").hover

I guess i could do it inside the each or try apply it afterwards (when all have been created) but im not sure how to go about it to get it to work


You can change it around a bit like this:

$("form input:text").each(function(index) {
  $("<span />", { "id": 'Span_' + this.id, text: $(this).val() })
    .insertAfter(this)
    .hover(function() {
      //do something
    });
  $(this).hide();
});

This uses $(html, props) to create the object, and instead of .after() uses .insertAfter(), that way your chain refers to the created element, so you can do whatever you want to it directly.


Since you're just hiding them and not detaching them, this should do the trick:

$("form input:text").each(function(index) {
    $(this).after("<span id='Span_" + $(this).attr("id") + "'>" + $(this).val() + "</span>").hide();
});
$("form input:text+span").hover(...);

Another alternative is using $(this).next().hover() inside the loop, after adding the element, like this:

$("form input:text").each(function(index) {
    $(this).after("<span id='Span_" + $(this).attr("id") + "'>" + $(this).val() + "</span>").hide().next().hover(...);
});

That is probably a better solution, since you get to bind the events individually. It adds unnecessary computations if you don't need to bind individually though.

0

精彩评论

暂无评论...
验证码 换一张
取 消