質問

Lets say I have this code:

<div id="Element_1" class="draggable">
<input type="text" placeholder="Enter Your Text Here" style="width:300px;">
</div>
<div id="Element_2" class="draggable">
<textarea placeholder="Enter Your Text Here" style="width:400px;height:200px;"></textarea>
</div>

What I am trying to do is get the element attribute values, from the child of the "div" and also the "Type" (Input/Tagname) so I can store the values in variables.

Currently I can get the element and store in a Var, this is the code I have:

$(".draggable").live("click",function(){
    var SelectedID = $(this).attr("id");
    $("*").removeClass("selected");   
    var Element = $("#"+SelectedID,":first-child").addClass("selected").html();

    PlaceholderPropValue = $(element).attr("placeholder");
    StylesPropValue = $(element).attr("style");
    WidthProp = StylesProp.match(/(width:)([0-9].*?)(?=px;)/)[2];
    HeightProp = StylesProp.match(/(height:)([0-9].*?)(?=px;)/)[2];
    alert(PlaceholderPropValue+ " " +WidthProp+ " " +HeightProp);
});

Thanks!

Carl

役に立ちましたか?

解決

Your code is kind of overkill.

  1. .live() is deprecated in jQuery 1.7 and totally removed in 1.9, jquery documentation says you should use .on() instead.
  2. Everything is simple. You can try something like:
$('.draggable').click(function(){
    var $element = $(this).children();
    var width = parseInt($element.width());
    var height = parseInt($element.height());
    var placeholder = $element.attr('placeholder');  
    alert(placeholder+ " " +width+ " " +height);
})
  • .children() method normally return set of element's children but there are only one in your example, so it's ok.
  • .width() and .height() returns values like "300px", so we use parseInt() to make int values.
  • .click(handler) is a shortcut for .on( "click", handler )
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top