-2

我做了这个示例代码:https ://jsfiddle.net/gwpcfp89/

问题是关于这个点击事件:

var wrapper = $(".select-editable"); // Fields wrapper

$(wrapper).on('keypress', '#input1', function () {
  var cs = $(this).val().length+1;
  console.log( "total caracters:" + cs);
  $('#mytext1').html('<option value="dummy01">dummy01</option><option value="dummy02">dummy02</option><option value="dummy03">dummy03</option>')
});

我使用#input1, #mytext1,并且我希望点击是动态的。例如:如果我在表中创建四个选择,则第四个选择应该像第一个选择(#input4#mytext4)一样具有单击事件。

可能吗?

4

3 回答 3

-1
I have modified you JSFiddle code - https://jsfiddle.net/pjf17exa/
As per your code, i have fixed some error and modified you code to make it dynamic input action.

// your code
var wrapper = $(".select-editable"); //Fields wrapper

$(wrapper).on('keypress', '#input1', function () {
var cs = $(this).val().length+1;
  console.log( "total caracters:" + cs);
  $('#mytext1').html('<option value="dummy01">dummy01</option><option 
  value="dummy02">dummy02</option><option 
  value="dummy03">dummy03</option>')
});

-- which assigns event for the current row, not for the dynamic elements. So instead take parent element and assign event for the input. Where you can access current element using $(this) instance inside the function. 

// do like this
var wrapper = $("#table-editable");
wrapper.on('keypress', 'input', function () {
  var cs = $(this).val().length+1;
  console.log( "total caracters:" + cs, $(this));
   $(this).prev().html('<option value="dummy01">dummy01</option><option value="dummy02">dummy02</option><option value="dummy03">dummy03</option>')
});
于 2017-06-19T13:32:57.687 回答
-1

你可以在这里做一个技巧。

当您创建动态选择标签时,为它们添加一个属性,例如:data-bind="<values>"

所以这里应该是您要附加的动态数字id以进行 input4

然后编写一个 jquery 函数,例如给这里:

$('select').click(function(){
    var clicked_select = $(this).attr('data-bind');
    // clicked_select will be the number which dynamic element you have clicked. You can use that number with id to access that particular element as a new selector.
});

这应该是您的解决方案。

于 2017-06-19T13:33:26.300 回答
-1

您的代码存在一些问题:

  1. 您分配给的字符串的data+=某些 HTML 属性使用双引号而不是单引号,因此导致代码中断。

  2. 您正在动态创建具有相同 ID 的输入字段。ID 属性在页面上应该始终是唯一的。为了解决这个问题,我使用该i+1变量将唯一编号附加到输入 ID。现在 ID 是唯一的,我必须将您更改$("#students").on('keypress', '#input1', function () {为,$("#students").on('keypress', 'input', function () {以便它通过标签名称选择元素。

  3. $(wrapper).on('keypress', 'input', function () {.select-editable用作事件处理程序,但.select-editable正在动态生成。事件处理程序必须是一个包含将要动态生成的所有元素的元素,而不是动态生成元素的一部分。所以我改变了代码的那部分来#students代替使用。

我希望这有助于解释问题所在。

https://jsfiddle.net/gwpcfp89/6/

于 2017-06-19T15:28:14.817 回答