动态生成的Jquery UI无法正常工作

时间:2014-06-08 02:06:06

标签: jquery jquery-ui

我有一些具有不同data-id的Jquery UI滑块。 如何检测选定对象并在其旁边的范围内返回滑块值?

我生成滑块和动态的其他元素:

<script>
$(function() {
$( "#slider" ).slider({
value:100,
min: 0,
max: 50000,
step: 50,
create: function () {
    $(this).slider( "option", "value", $(this).next().val() );
},
slide: function( event, ui ) {                 
     //get the id of this slider
var id = $(this).data('id');
     //select the input box that has the same id as the slider within it and set it's value to the current slider value. 
$("span[class*=" + id + "]").text(ui.value);
//$("div[class*=" + id + "]").val(ui.value);
}
});
});
</script>



<script>
$(document).ready(function() {
$("#adding").click(function() {

var intId = $("#buildyourform div").length + 1;
var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
var fName = $("<input type=\"text\" class=\"fieldname\" value=\"Enter your Facebook fan page url\" />");
var fType = $("<div id=\"slider\" datta-id=\"slider" + intId + "\" style='width:250px; float:left; margin-left:10px;'></div>").slider();
var fLikes= $("<span class=\"slider" + intId + "\" style=\"width: 60px; height: 24px; float: left; margin-left: 13px; margin-top: 7px; border: 1px solid #999; color: rgb(243, 20, 145); text-align: center; font-family: serif;\" />");
var fCost = $("<div class=\"fieldname\" id=\"fcost" + intId + "\" style=\"width: 60px; height: 24px; float: left; margin-left: 6px; margin-top: 7px; border: 1px solid #999; color: rgb(243, 20, 145); text-align: center; font-family: serif;\" />");
var removeButton = $("<input type=\"button\" class=\"remove\" value=\"-\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(fName);
fieldWrapper.append(fType);
fieldWrapper.append(removeButton);
fieldWrapper.append(fLikes);
fieldWrapper.append(fCost);
$("#buildyourform").append(fieldWrapper);
});
});
</script>

And inside the body:

<fieldset id="buildyourform">
<legend>Welcome! <span style="color:#F00; margin-left:13px;">My products</span></legend>
</fieldset>

<div id="adding"></div>

1 个答案:

答案 0 :(得分:1)

好的,为此,您可以创建一个全局变量,将所有滑块的公共属性存储为:

slider_options =
{
  value:100,
  min: 0,
  max: 50000,
  step: 50,
  orientation: "horizontal",
  create: function( e, ui ) {
    //was throwing TypeError: closestHandle is undefined with you previous code so i changed it to  
    var bar=$(this).slider('value');
 },
  slide: function( event, ui ) { 
      var id = $(this).data('id');
      $("span[class*=" + id + "]").text(ui.value);
   },
};

现在设置好了,您可以在slider()初始化代码中使用它:

var fType = $("<div id=\"slider\" data-id=\"slider" + intId + "\" style='width:250px; float:left; margin-left:10px;'></div>").slider(slider_options);

之后,您可以在滑块的data-id事件中获得所需的slide

这是Working Demo